手頭沒(méi)有Microsoft Access,如何建立數(shù)據(jù)庫(kù),一切依然簡(jiǎn)單.
首先引用C:Program FilesCommon FilesSystemadomsadox.dll,該DLL包含ADOX命名空間;
接著引用C:Program FilesCommon FilesSystemadomsjro.dll,該DLL包含JRO命名空間
SxS好問(wèn)提示:如,導(dǎo)入dll不成功,手動(dòng)把com組件導(dǎo)入為 .net組件,在用vs.net工具導(dǎo)入
using System;
using System.IO;
using ADOX; //該命名空間包含創(chuàng)建ACCESS的類(lèi)(方法)--解決方案 ==> 引用 ==> 添加引用 ==> 游覽找到.dll
using JRO; //該命名空間包含壓縮ACCESS的類(lèi)(方法)
public class Access
...{
/**////根據(jù)指定的文件名稱(chēng)創(chuàng)建ACCESS數(shù)據(jù)庫(kù)
///mdbPath:要?jiǎng)?chuàng)件的ACCESS絕對(duì)路徑
public void Create( string mdbPath )
...{
if( File.Exists(mdbPath) ) //檢查數(shù)據(jù)庫(kù)是否已存在
...{
throw new Exception("目標(biāo)數(shù)據(jù)庫(kù)已存在,無(wú)法創(chuàng)建");
}
// 可以加上密碼,這樣創(chuàng)建后的數(shù)據(jù)庫(kù)必須輸入密碼后才能打開(kāi)
mdbPath = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
// 創(chuàng)建一個(gè)CatalogClass對(duì)象的實(shí)例,
ADOX.CatalogClass cat = new ADOX.CatalogClass();
// 使用CatalogClass對(duì)象的Create方法創(chuàng)建ACCESS數(shù)據(jù)庫(kù)
cat.Create(mdbPath);
}
/**////壓縮修復(fù)ACCESS數(shù)據(jù)庫(kù),mdbPath為數(shù)據(jù)庫(kù)絕對(duì)路徑
public void Compact( string mdbPath )
...{
if( !File.Exists(mdbPath) ) //檢查數(shù)據(jù)庫(kù)是否已存在
...{
throw new Exception("目標(biāo)數(shù)據(jù)庫(kù)不存在,無(wú)法壓縮");
}
//聲明臨時(shí)數(shù)據(jù)庫(kù)的名稱(chēng)
string temp = DateTime.Now.Year.ToString();
temp += DateTime.Now.Month.ToString();
temp += DateTime.Now.Day.ToString();
temp += DateTime.Now.Hour.ToString();
temp += DateTime.Now.Minute.ToString();
temp += DateTime.Now.Second.ToString() + ".bak";
temp = mdbPath.Substring(0, mdbPath.LastIndexOf("")+1) + temp;
//定義臨時(shí)數(shù)據(jù)庫(kù)的連接字符串
temp2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + temp;
//定義目標(biāo)數(shù)據(jù)庫(kù)的連接字符串
mdbPath2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
//創(chuàng)建一個(gè)JetEngineClass對(duì)象的實(shí)例
JRO.JetEngineClass jt = new JRO.JetEngineClass();
//使用JetEngineClass對(duì)象的CompactDatabase方法壓縮修復(fù)數(shù)據(jù)庫(kù)
jt.CompactDatabase( mdbPath2, temp2 );
//拷貝臨時(shí)數(shù)據(jù)庫(kù)到目標(biāo)數(shù)據(jù)庫(kù)(覆蓋)
File.Copy( temp, mdbPath, true );
//最后刪除臨時(shí)數(shù)據(jù)庫(kù)
File.Delete( temp );
}
/**//// 備份數(shù)據(jù)庫(kù),mdb1,源數(shù)據(jù)庫(kù)絕對(duì)路徑; mdb2: 目標(biāo)數(shù)據(jù)庫(kù)絕對(duì)路徑
public void Backup( string mdb1, string mdb2 )
...{
if( !File.Exists(mdb1) )
...{
throw new Exception("源數(shù)據(jù)庫(kù)不存在");
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注