ASP.NET 連結 Access 伺服器 資料庫路徑問題
當做小項目用 ASP.NET + Access 資料庫時,總是遇到資料庫路徑問題,本人以前的解決方案是每次訪問資料庫時,把連結字串以參數的形式傳到資料訪問層,實施起來相當麻煩,這次找到了一個比較好的方案,這是本人目前的最終解決方案(如題) ^_^
解決方案為:
在 Web.Config 中配置 Access 資料庫驅動和資料庫檔案名稱。
請看代碼
<appSettings>
<add key="DBDriver" value="Provider=Microsoft.Jet.OLEDB.4.0; Data Source ="/>
<add key="DBName" value="Company.mdb"/>
</appSettings>
在資料庫訪問層,如 OleDBHelper.cs 中獲得 Access 資料庫連結字串。
/**//// <summary>
/// 從Web.Config取得資料庫聯結字串
/// </summary>
//從設定檔中得到資料庫名稱
public static readonly string DBName = ConfigurationManager.AppSettings.Get("DBName").ToString();
//從設定檔中得到資料庫驅動
public static readonly string DBDriver = ConfigurationManager.AppSettings.Get("DBDriver").ToString();
//得到資料庫連接字串
private static string DBConnectionString = DBDriver + HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "/App_Data/") + DBName;
//建立資料庫連接對象
private static OleDbConnection OleDbConn = new OleDbConnection(DBConnectionString);
這樣設定後,無論在任何子目錄,都能通過以上代碼正確的訪問資料庫。
引用地址:http://www.codesky.net/article/doc/201004/20100417061220.htm