C#中數據庫連接的配置文件


在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());
                }
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM