在C#2010中,如何保存和訪問數據庫的連接字符串呢?
在Winform下要新增App.config文件,在Asp.net下要新增web.config文件。
1.打開配置文件添加相關代碼后如下即可:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="myconn" connectionString="Data Source=.;Initial Catalog=Northwind; Persist Security Info=True;User ID=sa;Password=110"/> </connectionStrings> </configuration>
2.添加using System.Configuration;並在項目上右鍵“添加引用”->.Net組件中"Using Configuration"
如果不在組件中添加引用的話,后續的代碼編譯不過。
3.如下為讀取數據的相關代碼
private void button1_Click(object sender, EventArgs e) { string connstr = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString; using (SqlConnection conn = new SqlConnection(connstr)) { SqlCommand comm = new SqlCommand("select FirstName from Employees", conn); conn.Open(); SqlDataReader sdr = comm.ExecuteReader(); while (sdr.Read()) { listBox1.Items.Add(sdr[0].ToString()); } } }
