【Web.config檔案】
<connectionStrings>
<add name="MyBookstore_ConnectionString" connectionString="Data Source=127.0.0.1;Initial Catalog=MyBookstore;Persist Security Info=True;User ID=帳號;Password=密碼" providerName="System.Data.SqlClient" />
</connectionStrings>
【C#程式中引用】
Using System.Data.SqlClient;
【C#程式範例】
// 取得Web.config內的資料庫連線字串
string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["MyBookstore_ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
// 打開資料庫連線
con.Open();
using (SqlCommand command = new SqlCommand("SELECT TOP 10 [Book_No],[Book_Name],[Book_Price] FROM [Book] ORDER BY [Book_No]", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 讀取資料庫資料
Console.WriteLine("{0} {1} {2}", reader["Book_No"].ToString(), reader["Book_Name"].ToString(), reader["Book_Price"].ToString());
}
}
}
注意:
MyBookstore_ConnectionString: 取得資料庫連線的名稱需要一樣
留言列表