介紹
下面這段c# 代碼可以用來壓縮和修復access數據庫,不管它是一個簡單的".mdb"還是一個".mdw"網絡共享數據庫,這個過程和你在用ms access應用程序中使用的"工具-數據庫實用工具-壓縮和修復"時執行的操作完全一樣.實例代碼使用了"遲綁定"(運行中在內存中建立com對象),這樣就不需要在工程中加入com引用了,也不需要在pc上安裝ms access應用程序.只需要一個jet引擎(jet引擎包含在mdac安裝包中,在windows nt4以后的版本中,系統已經自帶了這個引擎).
背景
不知你是否也厭煩了在工程中加入復雜的com庫引用,但我相信這個純.net代碼將省去額外的交互操作, rcws和com引用.基本上,由于系統中安裝的microsoft類庫的不同(例如:ms office object library 9,10,11等等),我們也不知道用戶pc中安裝的office版本,所以我們要通過progid來訪問com對象,而不能用clsid.例如,當調用"excel.application
",時,得到的是excel,而不管系統中安裝ms office的版本,當在代碼中加入"ms excel 10 object library"引用時,其實只是給應用程序加入了一個非常受限制的功能.所以我們使用system.reflection
和遲綁定
.
1.
實例代碼
只需調用
compactaccessdb
函數即可壓縮和修復目標數據庫
.
2.
參數
:
由于jet引擎的限制,執行此方法壓縮access數據庫會把結果生成為一個新文件,所以我們要還需要把這個新的access文件拷貝到目的位置覆蓋原來未壓縮文件.
當調用此方法時請確認被壓縮數據庫無打開的連接.
代碼如下:
/// <summary>
/// mbd compact method (c) 2004 alexander youmashev
/// !!important!!
/// !make sure there's no open connections
/// to your db before calling this method!
/// !!important!!
/// </summary>
/// <param name="connectionstring">connection string to your db</param>
/// <param name="mdwfilename">full name
/// of an mdb file you want to compress.</param>
public static void compactaccessdb(string connectionstring, string mdwfilename){
object[] oparams;
//create an inctance of a jet replication object
object objjro =
activator.createinstance(type.gettypefromprogid("jro.jetengine"));
//filling parameters array
//cnahge "jet oledb:engine type=5" to an appropriate value
// or leave it as is if you db is jet4x format (access 2000,2002)
//(yes, jetengine5 is for jet4x, no misprint here)
oparams = new object[] { connectionstring, "provider=microsoft.jet.oledb.4.0;data" + " source=c://tempdb.mdb;jet oledb:engine type=5"}; //invoke a compactdatabase method of a jro object //pass parameters array
objjro.gettype().invokemember("compactdatabase",
system.reflection.bindingflags.invokemethod,
null,
objjro,
oparams);
//database is compacted now
//to a new file c://tempdb.mdw
//let's copy it over an old one and delete it
system.io.file.delete(mdwfilename); system.io.file.move("c://tempdb.mdb", mdwfilename); //clean up (just in case) system.runtime.interopservices.marshal.releasecomobject(objjro); objjro=null; } 注意事項 jet engine 5 用于 jet4x 數據庫. 使用時要留意下表: jet oledb:engine type jet x.x format mdb files 1 jet10 2 jet11 3 jet2x 4 jet3x 5 jet4x
原文鏈接: http://www.codeproject.com/cs/database/mdbcompact_latebind.asp
新聞熱點
疑難解答