Access “Compact and Repair” programmatically

前端 未结 7 651
逝去的感伤
逝去的感伤 2020-12-03 22:28

Is it possible to \"compact and repair\" an Access database programmatically somehow (using ADOX, using OleDbConnection etc.)?

7条回答
  •  借酒劲吻你
    2020-12-03 22:54

    It is just four lines of code in c#.net

    First use a library:

    using JRO;
    

    You want to compact and repair test.mdb with the following code:

    string currentdirectory = System.IO.Directory.GetCurrentDirectory();
    string oldmdbfile = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + currentdirectory + "\\test.mdb;Jet OLEDB:Database Password='xyz'";
    string newmdbfile = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + currentdirectory + "\\test1.mdb;Jet OLEDB:Database Password='xyz'";
    string oldmdbfilepath = currentdirectory + "\\test.mdb";
    string newmdbfilepath = currentdirectory + "\\test1.mdb";
    
    JRO.JetEngine engine = new JetEngine();
    engine.CompactDatabase(oldmdbfile, newmdbfile);
    File.Delete(oldmdbfilepath);
    File.Move(newmdbfilepath, oldmdbfilepath);
    MessageBox.Show("Database compact and repaired successfully !",);
    

    Thus test.mdb will be compacted and repaired and a new file test1.mdb will be created. Then you just have to delete test.mdb and rename test1.mdb to test.mdb.

提交回复
热议问题