在C#2013中,如何保存和访问数据库的连接字符串呢?
在Winform下要新增App.config文件,在Asp.net下要新增web.config文件。
1.打开配置文件添加相关代码后如下即可:
-
<?xml version="1.0" encoding="utf-8" ?>
-
<configuration>
-
<connectionStrings>
-
<add name="myconn" connectionString="Server=Datasvr;uid=mis;password=13456;Database=MIS" />
-
</connectionStrings>
-
</configuration>
2.添加using System.Configuration; 并在项目上右键“添加引用”->.Net组件中"Using Configuration"
如果不在组件中添加引用的话,后续的代码编译不过。
-
using system.configuration;
-
-
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());
-
}
-
}
-
}
阅读(5010) | 评论(0) | 转发(0) |