ASP.NET 2.0 遍曆設定檔的資料庫連接字串

來源:互聯網
上載者:User

在ASP.NET 2.0中,提供了更方便的設定檔訪問的類,具體可以到 System.Configuration 名稱空間下進行查看。本文提供一種在開發過程中常用的得到資料庫字串的方法,為方便使用,寫成一個方法進行調用:

public string GetConnectionString( string _connectionStringsName )
{
  System.Configuration.ConnectionStringSettingsCollection config = System.Configuration.ConfigurationManager.ConnectionStrings;
  for (int i = 0 ; i < config.Count ; i++)
  {
    if (config[i].Name.Equals(_connectionStringsName, StringComparison.OrdinalIgnoreCase))
      return config[i].ToString();
  }
  return String.Empty;
}

如果web.config配置如下:

<connectionStrings>
    <add name="ConnectionString1" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase1;Server=(local);" providerName="System.Data.SqlClient"/>
    <add name="ConnectionString2" connectionString="Persist Security Info=False;User ID=sa;Password=;Initial Catalog=DataBase2;Server=(local);" providerName="System.Data.SqlClient"/>
</connectionStrings> 

如果寫成靜態類方法,則可以使用下面的方法進行調用:

string ConnectString = XianhuiMengUtil.GetConnectionString("ConnectionString1");

另外,如果在遍曆時進行輸出,則可以看到多出來一個配置項,那是因為machine.config裡已經預設定義理一個資料庫連接,內容如下:

<connectionStrings>
  <add name="LocalSqlServer" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>

這就是許多網友在論壇上經常會問:為什麼我的程式會調用 SQLEXPRESS 資料庫的原因,如果你的資料庫配置不正確,或者無法開啟時,就會使用 SQLEXPRESS 資料庫。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.