Chinaunix首页 | 论坛 | 博客
  • 博客访问: 511981
  • 博文数量: 88
  • 博客积分: 2256
  • 博客等级: 大尉
  • 技术积分: 921
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-08 23:20
个人简介

积硅步,行千里

文章分类

全部博文(88)

文章存档

2019年(5)

2018年(1)

2016年(15)

2015年(23)

2013年(3)

2012年(6)

2011年(3)

2010年(22)

2009年(10)

我的朋友

分类: C#/.net

2015-04-29 13:09:19

在C#2013中,如何保存和访问数据库的连接字符串呢?
在Winform下要新增App.config文件,在Asp.net下要新增web.config文件。
1.打开配置文件添加相关代码后如下即可:

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3.   <connectionStrings>
  4.     <add name="myconn" connectionString="Server=Datasvr;uid=mis;password=13456;Database=MIS" />
  5.   </connectionStrings>
  6. </configuration>
2.添加using System.Configuration;   并在项目上右键“添加引用”->.Net组件中"Using Configuration"
如果不在组件中添加引用的话,后续的代码编译不过。

点击(此处)折叠或打开

  1. using system.configuration;

  2. private void button1_Click(object sender, EventArgs e)
  3.         {
  4.             string connstr = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
  5.             using (SqlConnection conn = new SqlConnection(connstr))
  6.             {
  7.                 SqlCommand comm = new SqlCommand("select FirstName from Employees", conn);
  8.                 conn.Open();
  9.                 SqlDataReader sdr = comm.ExecuteReader();
  10.                 
  11.                 while (sdr.Read())
  12.                 {
  13.                     listBox1.Items.Add(sdr[0].ToString());
  14.                 }
  15.             }
  16.         }


阅读(4914) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~