在ASP.NET中,通過Web.config,你可為使用 <appSettings> 標記,在這個標記中,你可用 <add ... /> 標記定義0到多個設置。本文中我們主要討論了如何使用web.config來配置一個web應用程序中的數據庫連接。
web.config文件是標準的xml文件,我們可以使用它來為一臺機器下的每一個web應用程序或某個應用程序或一個目錄下的asp.net頁面來進行設置,當然,它也可以為一個單獨的web頁面進行設置。
如:網站的主目錄是\inetpub\wwwroot\,那么我們將web.config放置于其下,那么這個網站中的應用程序將被web.config中的設置所影響。
e.g.:
<?xml version="1.0" encoding="gb2312" ?>
<configuration>
<system.web>
<compilation defaultlanguage="vb" debug="true" />
<customerrors mode="remoteonly" defaultredirect="js/error.htm">
<error statuscode="404" redirect="js/filenotfound.aspx" />
<error statuscode="500" redirect="js/error.htm" />
</customerrors>
<authentication mode="windows" />
<authorization>
<allow users="*" />
</authorization>
<httpruntime maxrequestlength="4000" usefullyqualifiedredirecturl="true" executiontimeout="45" />
<trace enabled="false" requestlimit="10" pageoutput="false" tracemode="sortbytime" localonly="true" />
<sessionstate mode="inproc" stateconnectionstring="tcpip=127.0.0.1:43444" cookieless="false" timeout="20" />
<globalization requestencoding="gb2312" responseencoding="gb2312" fileencoding="gb2312" />
</system.web>
<appsettings>
<add key="connstring" value="uid=flash;password=3.1415926;database=news;server=(local)" />
</appsettings>
</configuration>
這里我們討論一下如何在web.config中設置數據庫連接。
1、連接一個數據庫:
在web.config中的<configuration>后加入
<appsettings>
<add key="connstring"
value="uid=flash;password=3.1415926;database=news;server=(local)" />
</appsettings>
在程序中,你可以使用以下代碼來使用web.config中的設置:
-----vb.net-----
imports system.configuration
dim myvar as string
myvar=configurationsettings.appsettings("connstring"
-----c#-----
using system.configuration;
string myvar;
myvar=configurationsettings.appsettings["connstring"];
2、連接多個數據庫
同理,那就是使用多個不同的key值來設置
3、設置不同子目錄下應用程序的數據庫鏈接
這是一個很有意思的方法,在設置前,先說明一下它的用途:
如果在一個虛擬目錄下有多個子目錄,每一個子目錄下下的web應用程序都需要連接不同的數據庫,這如何做呢??
一種方法是在每一個子目錄下分別建立一個web.config,用它來設置這個目錄下的數據庫連接。但這種方法的問題是需要維護每一個了目錄下的web.config。
方法二,是只在虛擬目錄下建立一個web.config,在它里面設置每一個子目錄下的應用程序的數據庫連接。說到這里,你會想到上面的第二種方法,使用多個不同的key值來設置,這的確是一個辦法。
這里,我想說明的是另一種方法:在虛擬目錄下布置web.config,在其中使用location標記,使用同一個key值來連接數據庫,這樣做的好處很明顯,因為用同一個key值,將導致在所有目錄下的應用程序中,都可以使用共同的語句來連接數據庫,這在程序以后發生位置遷移時,并不用修改程序中連接數據庫的語句。
具體設置如下:
<location path="news">
<appsettings>
<add key="connstring" value="uid=flyangel;password=3.1415926;database=news;server=(local)" />
</appsettings>
</location>
<location path="bbs">
<appsettings>
<add key="connstring" value="uid=flyangel;password=3.1415926;database=bbs;server=(local)" />
</appsettings>
</location>
<location path="soft">
<appsettings>
<add key="connstring" value="uid=flyangel;password=3.1415926;database=soft;server=(local)" />
</appsettings>
</location>
注:上例中news、bbs、soft分別是虛擬目錄下的子目錄。
程序中使用連接時,采用下面的方法:
public function getconnectionstring()
configurationsettings.appsettings().item("connstring"
end sub
最后需要說明的一點是,為了有效地利用.config文件,你應當創建標準的鍵名和值定義供所有的應用程序開發人員所用。這樣就可以讓同一項目的開發人員采用公共的項目設置。這些標準在部署應用程序和將其轉化為產品的時候非常有用。