asp.net|字串
在ASP.NET 2.0中,使用了一種在運行時解析為連接字串值的新的聲明性運算式文法,按名稱引用資料庫連接字串。連接字串本身儲存在 Web.config 檔案中的 <connectionStrings> 配置節下面,以便易於在單個位置為應用程式中的所有頁進行維護。
範常式序代碼如下:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="Pubs" connectionString="Server=localhost;
Integrated Security=True;Database=pubs;Persist Security Info=True"
providerName="System.Data.SqlClient" />
<add name="Northwind" connectionString="Server=localhost;
Integrated Security=True;Database=Northwind;Persist Security Info=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<pages styleSheetTheme="Default"/>
</system.web>
</configuration>
程式碼說明:在上述範例的程式碼中,我們在Web.Config檔案中的<connectionStrings> 配置節點下面設定了兩個資料庫連接字串,分別指向pubs和Northwind兩個樣本資料庫。注意,在2.0中引進了資料來源控制項,例如SqlDataSource 控制項,我們可以將SqlDataSource 控制項的 ConnectionString 屬性被設定為運算式 <%$ ConnectionStrings:Pubs %>,該運算式在運行時由 ASP.NET 分析器解析為連接字串。還可以為SqlDataSource 的 ProviderName 屬性指定一個運算式,例如 <%$ ConnectionStrings:Pubs.ProviderName %>。其具體的用法和新特徵將在以後的章節進行詳細的介紹。現在有個基礎的瞭解即可。
當然,我們也可以用下面的方式從設定檔直接讀取資料庫連接字串。首先我們需要引用using System.Web.Configuration命名空間,該命名空間包含用於設定 ASP.NET 配置的類。
string connectionString =ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
程式碼說明:在上述範例的程式碼中,我們可以利用ConnectionStrings["Northwind"]讀取相應的Northwind字串。同理以可以利用ConnectionStrings["Pubs"]讀取相應的Pubs字串。