asp.net Web.Config使用
在web.config中使用象ASP那样的Server.MapPath取数据库路径
但web.config不认识Server.MapPath,此方法致使程序无法调试,行不通。
如下方法,可以方便的移植程序路径而不必再去修改ACCESS数据库路径。
在web.config中的写法如下:
<appSettings>
<add key="ConnStr" value="provider=microsoft.jet.oledb.4.0;data source="/>
<add key="dbPath" value="/AppData/mydata.mdb"/>
</appSettings>
<add key="ConnStr" value="provider=microsoft.jet.oledb.4.0;data source="/>
<add key="dbPath" value="/AppData/mydata.mdb"/>
</appSettings>
程序中的数据访问类中我把"ConnStr"和"dbPath"取出来再连接成一个字符串
代码如下:
/// <summary>
/// (静态)返回数据库连接串。
/// </summary>
protected static string GetConnString()
{
return
System.Configuration.ConfigurationSettings.AppSettings["ConnStr"]+ System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["DataPath"])+";";
}
/// (静态)返回数据库连接串。
/// </summary>
protected static string GetConnString()
{
return
System.Configuration.ConfigurationSettings.AppSettings["ConnStr"]+ System.Web.HttpContext.Current.Server.MapPath(System.Configuration.ConfigurationSettings.AppSettings["DataPath"])+";";
}
在web.config文件里添加关键字key是通过<appSettings>标记来实现的,但是appSettings标记通常放在<system.web>.....</system.web>标记外面。例:
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
程序中这样调用
using System.Configuration;
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);