標籤:
先引用
using System.Configuration;//設定檔
using System.Data.SqlClient;
我這裡使用的是SqlServer 2008 sa 使用者 密碼也為sa, 開發工具為visual studio2012
前台代碼:
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;//Mysqlusing MySql.Data.MySqlClient;//Sqlusing 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
C# asp.net 設定檔串連sql 資料庫