先引用
using System.Configuration;//配置文件
using System.Data.SqlClient;
我这里使用的是SqlServer 2008 sa 用户 密码也为sa, 开发工具为visual studio2012
前台代码:Web.config配置文件
1 <connectionStrings> 2 <!--<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-配置文件链接数据库-20150623105832;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-配置文件链接数据库-20150623105832.mdf" />--> 3 <add name="myconn" connectionString="Data Source=.;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa ; Database=test1"/> 4 </connectionStrings>
后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; //using MySql.Data.MySqlClient;//Mysql using MySql.Data.MySqlClient;//Sql using System.Configuration;//配置文件 using System.Data.SqlClient; namespace 配置文件链接数据库 { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //获取配置文件中的连接字符串 string constr = ConfigurationManager.ConnectionStrings["myconn"].ToString(); using (SqlConnection con=new SqlConnection(constr)){ string selstr = "select name from user1 where 1=1"; SqlCommand com = new SqlCommand(selstr,con); con.Open(); SqlDataReader sdr = com.ExecuteReader(); while (sdr.Read()){ ListBox1.Items.Add(sdr[0].ToString()); } } Response.Write(constr); } } }
这里感谢 科员前人的经验:http://www.cnblogs.com/yagzh2000/archive/2013/03/13/2957266.html