在寫一套系統時,常常會遇到因環境不同而需要進行系統資料庫連線字串
如果將系統資料庫連線字串都寫在.CS檔中,那就必須每次修改後,重新編譯和發行
因此這時候這些系統資料庫連線字串就可以寫在Web.config中
不需要進行編譯與發行就能調整系統資料庫連線字串參數
撰寫ConnectionString (資料庫連線字串)只需要在Web.config底下的之間
加入<connectionStrings>節點…</connectionStrings>即可
Web.config文件資料庫連線字串的ConnectionString
<connectionStrings> <add name="ConnDB" connectionString="Data Source=資料庫主機名稱或位址;Initial Catalog=資料庫名稱;Persist Security Info=True;User ID=帳號;Password=密碼" providerName="System.Data.SqlClient"/> </connectionStrings>
ASP.NET Web窗體和MVC中的C#讀取
System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnDB"].ConnectionString;
ASP.NET的WinForm的C#讀取
System.Configuration.ConfigurationManager.ConnectionStrings["ConnDB"];
ASP.NET Web窗體和MVC為VB讀取
System.Web.Configuration.WebConfigurationManager.ConnectionStrings("ConnDB").ConnectionString
ASP.NET的WinForm為VB讀取
System.Configuration.ConfigurationManager.ConnectionStrings("ConnDB")