ASP.NET Web.config 取得 ConnectionString 參數

在寫一套系統時,常常會遇到因環境不同而需要進行系統資料庫連線字串

如果將系統資料庫連線字串都寫在.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")
訂閱
通知
guest
0 留言
預約回饋
查看所有留言