在web.config文件里添加关键字key是通过<appSettings>标记来实现的,但是appSettings标记通常放在<system.web>.....</system.web>标记外面。例:
<configration>
<appSettings>
<add key="connString1"
value="server=localhost;user id=sa;pwd=;database=数据库名字"/>
<add key="connString2"
value="provider=Microsoft.Jet.OleDb.4.0;Data Source=数据库路径"/>
</appSettings>
<system.web>
要在代码中引用这些数据库连接字符串,需要先添加对System.ConFiguration名字空间的引用,在这个名字空间中含有ConfigurationSettings类,其静态方法ConfigurationSettings.AppSettings属性可获取web.config文件中<appSettings>节的设置,读到的值为string型。例如:
using System.Configuration;
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);
.
.
.
</system.web>
</configration>
……