方法1:
Web.config中這樣寫
調用代碼這樣寫
OleDbConnection conn = new OleDbConnection(ConfigurationSettings.AppSettings["oleDSN"]+Server.MapPath(ConfigurationSettings.AppSettings["oleFile"].Trim()));
在Web.config中配置的好處就是以后修改數據庫路徑不用重新編譯,只需要在Web.config中修改一下就可以來,不過注意最好用UltraEdit之類的文本編輯器修改,因為他是utf-8編碼的。
方法2:
其實方法2與方法1是一樣的,只不過不用在Web.config配置了,寫的比較呆板。
string strConn = Server.MapPath("~/DataBase/weste_net.mdb;");
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source="+strConn);
方法3:
///獲得連接字符串
public string GetConnectionString()
{
string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Getmdbfilepath();
return strConnectionString;
}
///組合連接字符。
private string Getmdbfilepath(){
string strfilepath = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;//判斷當前進程的位置
strfilepath = strfilepath.Remove(0,8);//去掉路徑前面的"file:///"
strfilepath = strfilepath.Remove(strfilepath.Length-18,18);//去掉實際生成的dll文件和bin路徑,如"/bin/weste_net.DLL",可以靈活處理
strfilepath = strfilepath + "\\DataBase\\weste_net.mdb";
strfilepath = Regex.Replace(strfilepath,"/","\\");
return strfilepath;
}
方法3比較麻煩,只不過提出另一種思路。
轉載本文請注明來自西部e網 www.wsalc.com
提示所需要的命名空間:
using System.Web;
HttpContext.Current.Server.MapPath();
//為當前 HTTP 請求獲取 HttpContext 對象。
using System.Configuration;
//System.Configuration 命名空間提供類和接口,用于以編程方式訪問 .NET Framework 配置設置和處理配置文件(.config 文件)中的錯誤。
ConfigurationSettings.AppSettings[];
using System.Data.OleDb;
//使用Access數據庫。System.Data.OleDb 命名空間是用于 OLE DB 的 .NET Framework 數據提供程序。
