标题 | 用c#压缩和修复access数据库 |
内容 | 介绍 下面这段c# 代码可以用来压缩和修复access数据库,不管它是一个简单的.mdbaccess数据库还是一个.mdw网络共享数据库,这个过程和你在用ms access应用程序中使用的工具-数据库实用工具-压缩和修复时执行的操作完全一样.实例代码使用了迟绑定(运行中在内存中建立com对象),这样就不需要在工程中加入com引用了,也不需要在pc上安装ms access应用程序.只需要一个jet引擎(jet引擎包含在mdac安装包中,在windows nt4以后的版本中,系统已经自带了这个引擎). c#操作access数据库的背景 不知你是否也厌烦了在工程中加入复杂的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. 参数: connectionstring – 用来连接到access数据库. mdwfilename –要压缩的mdb文件的全名(路径+文件名). 由于jet引擎的限制,执行此方法压缩access数据库会把结果生成为一个新文件,所以我们要还需要把这个新的access文件拷贝到目的位置覆盖原来未压缩文件. 当调用此方法时请确认被压缩数据库无打开的连接. /**//// mbd compact method (c) 2004 alexander youmashev /// !!important!! /// !make sure there's no open connections /// to your db before calling this method! /// !!important!! /// /// connection string to your db /**//// full name /**//// of an mdb file you want to compress. 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; } |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。