方法1:
Web.config中這樣寫
調(diào)用代碼這樣寫
OleDbConnection conn = new OleDbConnection(ConfigurationSettings.AppSettings["oleDSN"]+Server.MapPath(ConfigurationSettings.AppSettings["oleFile"].Trim()));
在Web.config中配置的好處就是以后修改數(shù)據(jù)庫(kù)路徑不用重新編譯,只需要在Web.config中修改一下就可以來(lái),不過(guò)注意最好用UltraEdit之類的文本編輯器修改,因?yàn)樗莡tf-8編碼的。
方法2:
其實(shí)方法2與方法1是一樣的,只不過(guò)不用在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;//判斷當(dāng)前進(jìn)程的位置
strfilepath = strfilepath.Remove(0,8);//去掉路徑前面的"file:///"
strfilepath = strfilepath.Remove(strfilepath.Length-18,18);//去掉實(shí)際生成的dll文件和bin路徑,如"/bin/weste_net.DLL",可以靈活處理
strfilepath = strfilepath + "\\DataBase\\weste_net.mdb";
strfilepath = Regex.Replace(strfilepath,"/","\\");
return strfilepath;
}
方法3比較麻煩,只不過(guò)提出另一種思路。
轉(zhuǎn)載本文請(qǐng)注明來(lái)自西部e網(wǎng) virtualinteriordefine.com
提示所需要的命名空間:
using System.Web;
HttpContext.Current.Server.MapPath();
//為當(dāng)前 HTTP 請(qǐng)求獲取 HttpContext 對(duì)象。
using System.Configuration;
//System.Configuration 命名空間提供類和接口,用于以編程方式訪問(wèn) .NET Framework 配置設(shè)置和處理配置文件(.config 文件)中的錯(cuò)誤。
ConfigurationSettings.AppSettings[];
using System.Data.OleDb;
//使用Access數(shù)據(jù)庫(kù)。System.Data.OleDb 命名空間是用于 OLE DB 的 .NET Framework 數(shù)據(jù)提供程序。