您的位置:首页 > 数据库

今天 学习 web.config 配置数据库,奥耶

2010-01-20 13:28 411 查看
web.config文件是标准的xml文件,

我们可以使用它来为一台机器下的每一个web应用程序或某个应用程序或一个目录下的asp.net页面来进行设置,

当然,它也可以为一个单独的web页面进行设置。

 

在<configuration> 中添加 ,红色为添加的部分

 

<?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>后加入

-----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文件,你应当创建标准的键名和值定义供所有的应用程序开发人员所用。这样就可以让同一项目的开发人员采用公共的项目设置。这些标准在部署应用程序和将其转化为产品的时候非常有用。

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息