码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2014-06-26 12:58:38      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:winform   style   class   blog   code   http   

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

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

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

bubuko.com,布布扣
<?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>
bubuko.com,布布扣

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

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

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

bubuko.com,布布扣
 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());
                }
            }
        }
bubuko.com,布布扣

 

C#中数据库连接的配置文件,布布扣,bubuko.com

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

标签:winform   style   class   blog   code   http   

原文地址:http://www.cnblogs.com/milantgh/p/3809305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!