本文中我们主要讨论了如何使用web.config来配置一个web应用程序中的数据库连接。web.config文件是标准的xml文件,我们可以使用它来为一台机器下的每一个web应用程序或某个应用程序或一个目录下的asp.net页面来进行设置,当然,它也可以为一个单独的web页面进行设置。如:网站的主目录是\inetpub\wwwroot\,那么我们将web.config放置于其下,那么这个网站中的应用程序将被web.config中的设置所影响。
<?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=sa;password=sa;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中的设置:
//引用命名空间 using system.configuration; string conString;
conString = ConfigurationManager.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 void getconnectionstring(){ configurationsettings.appsettings().item("connstring") }
最后需要说明的一点是,为了有效地利用.config文件,你应当创建标准的键名和值定义供所有的应用程序开发人员所用。这样就可以让同一项目的开发人员采用公共的项目设置。这些标准在部署应用程序和将其转化为产品的时候非常有用。