C#要如何引用Web.Config的 connectionString?
在做ASP.NET網頁設計時常常會需要用到connectionString,需要用到connectionString時比較好的做法是去引用Web.config的connectionString,今天就來教大家ASP.NET使用C#程式要如何引用Web.config的connectionString。
首先在Web.config檔案裏面加入下面這串程式,這裡要注意MVC的Web.config有2個,這裡不是改在View資料夾裡面的Web.config,是要改不在資料夾內的那個Web.config。在View資料夾裡面的Web.config只有View會用到而已,而直接放在專案下面的Web.config大家都能用到,我想這個應該也滿好理解的。
<connectionStrings>
<add name="connstring" connectionString="Persist Security Info=False; Integrated Security=true; Initial Catalog=你的資料表名稱; Server=你的資料庫路徑; User ID=帳號;Password=密碼" providerName="System.Data.SqlClient"/>
</connectionStrings>
這邊其實如果有設定Integrated Security=true的話SQL Sever就可以用Windows驗證不需要帳號密碼,這樣的話User ID和Password這2個是可以刪掉不用輸入的。
然後在C#的程式中,先引用System.Data.SqlClient,程式如下:
using System.Data.SqlClient;
然後輸入下面的程式:
private readonly string cnstr = System.Web.Configuration.WebConfigurationManager.
ConnectionStrings["connstring"].ConnectionString;
string sql = @"Select * from Guestbooks"; //這裡輸入要執行的TSQL
SqlConnection conn = new SqlConnection(cnstr);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
.
.
.
cmd.Dispose();
conn.Close();
這樣就可以引用Web.config的connectionString了,當然如果是MVC的話不需要輸入TSQL指令,有其他的方式可以取代,今天只是做引用Web.config的connectionString教學,有關於MVC中怎麼使用資料庫的部分,有空我會再整理一篇給大家。