close
web.config相關設定-1
在單一平台上會抓的資料庫通常都同一資料庫
這時候用web.config作設定是挺適合的
畢竟設定都寫在web.config裡
要修改設定也不用每個檔都去做修改
在維護上也比較方便
以下是大略的程式碼
在web.config檔的部份
<connectionStrings> <add name="testdb" connectionString="Initial Catalog=DBname;Persist Security Info=True;User ID=sa;Password=112233" providerName="System.Data.SqlClient"/> </connectionStrings> |
name的部份名稱是自行決定的,在.cs檔的時候就是以這個名稱來連結。
其餘的相關設定可參考MSDN
.cs檔的部份
一樣要先using System.Data.SqlClient這個命名空間
然後連線的方法如下
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testdb"].ConnectionString); |
其中紅字的自訂名稱需跟web.config中的name相同才可成功連線。
範例:
void opendb()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["testdb"].ConnectionString);
conn.Open(); SqlCommand cmd = new SqlCommand("select * from employee", conn); DataSet ds = new DataSet(); SqlDataAdapter adpt = new SqlDataAdapter(cmd); SqlCommandBuilder cd = new SqlCommandBuilder(adpt); adpt.Fill(ds, "emp"); conn.Close(); } |
延伸閱讀
全站熱搜