在WebConfig中設定資料庫連接字串,代碼如下:
複製代碼 代碼如下:
<connectionStrings>
<add name="ConnectionString" connectionString="user id=使用者名稱;password=密碼;initial catalog=資料庫名稱;data source=伺服器名稱"/>
</connectionStrings>
然後在Webform_1.aspx.cs裡面擷取連接字串,要添加如下引用;
複製代碼 代碼如下:
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
代碼:
複製代碼 代碼如下:
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
ConnectDB();
}
private void ConnectDB()
{
string ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
con = new SqlConnection(ConString);
con.Open();
SqlCommand com = new SqlCommand();
SqlDataReader sdr;
string sqlstr = "select * from item";
com.CommandText = sqlstr;
com.Connection = con;
sdr = com.ExecuteReader();
while (sdr.Read())
{
Response.Write(sdr["欄位名"].ToString()+"</br>");
}
sdr.Close();
sdr = null;
}