C#中数据库连接的配置文件

时间:2023-03-09 22:35:54
C#中数据库连接的配置文件

在C#2010中,如何保存和访问数据库的连接字符串呢?

在Winform下要新增App.config文件,在Asp.net下要新增web.config文件。

1.打开配置文件添加相关代码后如下即可:

C#中数据库连接的配置文件
<?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>
C#中数据库连接的配置文件

2.添加using System.Configuration;并在项目上右键“添加引用”->.Net组件中"Using Configuration"

如果不在组件中添加引用的话,后续的代码编译不过。

3.如下为读取数据的相关代码

C#中数据库连接的配置文件
 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());
}
}
}
C#中数据库连接的配置文件