Click here to Skip to main content
Click here to Skip to main content

How to Compact Microsoft Access Database Using Visual Studio.NET

By , 8 Jun 2006
 

Introduction

When you use Microsoft Access database, you may have noticed that file size always keeps growing and you can never decrease the size. Even if you delete some entries and tables, the size remains the size or sometimes grows despite the deletion. You then need to compact your database. Using the compact utility, the file size decreases to a large extent.

Background

Microsoft Access database creates this situation when you use an open connection very frequently or open the connection several times to communicate with the database. The very definite reason of size increasing is that your database is really of large size and is increasing. All three situations can be handled using the compact utility. In my previous article, I describe how to create and populate a Microsoft Access file. While doing this, I came to know that the file size is really so large and used the compact feature to reduce the size. It was an amazingly big difference, so then I decided to compact that automatically.

Requirements

For the development of this utility, you need to add a reference to the DOA Library. DOA library provides the functionality to compact the database. One more thing that may be interesting is the database file that you want to compact should be of large size, otherwise you will not feel the effect.

Code

VB

Imports System.IO
Module Module1
    Sub Main()
        Try
            Dim File_Path, compact_file As String
            'Original file path that u want to compact
            File_Path = AppDomain.CurrentDomain.BaseDirectory & "db.mdb"
            'compact file path, a temp file
            compact_file = AppDomain.CurrentDomain.BaseDirectory & "db1.mdb"
            'First check the file u want to compact exists or not
            If File.Exists(File_Path) Then
                Dim db As New DAO.DBEngine()
                'CompactDatabase has two parameters, creates a copy of 
                'compact DB at the Destination path
                db.CompactDatabase(File_Path, compact_file)
            End If
            'restore the original file from the compacted file
            If File.Exists(compact_file) Then
                File.Delete(File_Path)
                File.Move(compact_file, File_Path)
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Module

C#

using System.IO; 
struct Module1 
{ 

 void Main() 
 { 
   try { 
     string File_Path; 
     string compact_file; 
     File_Path = AppDomain.CurrentDomain.BaseDirectory + "db.mdb"; 
     compact_file = AppDomain.CurrentDomain.BaseDirectory + "db1.mdb"; 
     if (File.Exists(File_Path)) { 
       DAO.DBEngine db = new DAO.DBEngine(); 
       db.CompactDatabase(File_Path, compact_file);  
     } 
     if (File.Exists(compact_file)) { 
       File.Delete(File_Path);
       File.Move(compact_file, File_Path); 
     } 
   } catch (Exception ex) { 
     MsgBox(ex.Message); 
   } 
 } 
}

Points of Interest

Using this utility, you can schedule a job to compact your database. But remember to schedule this at some specific time when you feel the database may not be in use as this compact utility deletes the original file and restores it with the compact one.

Summary

To use this utility, you do not need to do it yourself. Rather, you only need to schedule a job and relax. Happy programming.

History

  • 9th June, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Malik Nasir
Team Leader ZonG, China Mobile Company
Pakistan Pakistan
Member
I am currently based in Islamabad,Pakistan. I have done my MS Computer Science and I am involved in Microsoft Visual Studio.net Windows/Web application development since 2003 untill that i have been working in VB, ASP and web scripting languages. Currently i am working in ZonG as Team LEad IT Projects and Planing. I am also the administrator of Business Process

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThank you very muchmemberramugaru9 Dec '06 - 7:54 
Thank you very much malik
 
ramu

GeneralI've found a solution, here it is [modified]memberMartijn Groen16 Oct '06 - 22:43 
I've answered my own question. This does the job the same way but using a different method. This has gotten around the password protected database problem I was having when compacting the database. Personal thanks to Malik Nasir for writing an informative & helpful article,
 
regards
 
Martijn
 
'Visual Basic.NET
 
Dim jro As JRO.JetEngineClass
Dim newConnectionString As String
Dim connectionString As String
 
Dim directorypath As String = "C:\"
Dim originalDB As String = "mydatabase.mdb"
Dim newDB As String = "temp.mdb"
 
'instantiate the Jet Replication Object
jro = New JRO.JetEngineClass()
 
'get connection string for original database
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\mydatabase.mdb; Jet OLEDB:Database Password=secret;"
'create a connection string for the compacted and repaired database we are going to create
newConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\temp.mdb; Jet OLEDB:Database Password=secret;Jet OLEDB:Engine Type=5;"
 
'check to see if the temp database exists from previous database compacting incase it failed to copy back
'if it does exisit then it must first be deleted before executing the database compact to stop it throwing an exception
If IO.File.Exists(directorypath + newDB) Then
IO.File.Delete(directorypath + newDB)
End If
 
'now lets compact the original database to our new one
jro.CompactDatabase(connectionString, newConnectionString)
 
'overwrite the original Database file with the compacted one
If IO.File.Exists(directorypath + newDB) Then
IO.File.Delete(directorypath + originalDB)
IO.File.Move(directorypath + newDB, directorypath + originalDB)
End If
 

-- modified at 3:39 Sunday 10th December, 2006
GeneralAdditional note about adding the JRO objectmemberMartijn Groen9 Dec '06 - 21:37 
I did it using visual studio 2005. It should also work with the express versions of visual basic and visual web developer.
 
1) Open your project in Visual Studio .NET
2) Right click References in the Solution Explorer and select 'Add Reference...'
3) Click the COM tab and select 'Microsoft Jet and Replication Objects 2.x Library' 'x' will be the version you have.
4) Click the Select button and then Ok.
 
Now you should have references to ADODB and JRO added to your project. This will drop the Interop.JRO.dll in your bin folder and you should be in business using the code I posted.
 
You may also need to look at importing the following name spaces if you havent already done so in your web config.
 
System
 
System.IO
 
System.Configuration;
 

 
Martijn
Generalnice jobmemberKali Babu12315 Jun '06 - 21:24 
Smile | :)
QuestionIs Interop.DAO.dll part of VS2005member*chopper*13 Jun '06 - 21:11 
Small but nice
 
unfortunately, there is no reference mentioning which Visual Studio (2003 or 2005) you have used or recommend for this solution.
 
I tried to find a reference to interop.dao from within VS2005, but could not find it. After I downloaded your project demo, I used the included interop.dao.dll, but as I am a newbie, I am not sure in doing right.
 
I have another to compact access mdb using JRO.JetEngine. Is this better in VS2005 (writing VB)?
 
hjg
AnswerRe: Is Interop.DAO.dll part of VS2005memberMalik Nasir13 Jun '06 - 23:29 
please check at the following location C:\Program Files\Common Files\Microsoft Shared\DAO
this is not in .net references
and the code mentioned work for both the versions
 
Regards
GeneralRe: Is Interop.DAO.dll part of VS2005member*chopper*14 Jun '06 - 1:03 
Thanks for the help
 
Although I find the files
 
C:\Programme\Gemeinsame Dateien\Microsoft Shared\DAO\DAO2535.TLB
C:\Programme\Gemeinsame Dateien\Microsoft Shared\DAO\DAO3032.DLL
C:\Programme\Gemeinsame Dateien\Microsoft Shared\DAO\DAO350.DLL
C:\Programme\Gemeinsame Dateien\Microsoft Shared\DAO\dao360.dll
 
none of them resolve the issue with DAO.DBEngine (ambiguous name in namespace DAO) in VS 2005, when added as reference and an additional "imports DAO" at the beginning of the code.
 
regards
 
Josef
GeneralRe: Is Interop.DAO.dll part of VS2005 [modified]memberZeshan Sadiq19 Aug '07 - 16:06 
Thanks really helpful for me...
zeshan sadiq
modified on Friday, June 3, 2011 7:31 PM

GeneralCheckmemberSteve Hansen8 Jun '06 - 22:26 
You might want to check if the compact file was created before deleting the original Smile | :)
GeneralRe: CheckmemberMalik Nasir8 Jun '06 - 22:30 
good point Smile | :) i will make changes
but compact always creates a file so i did not bothered myself Smile | :)
 
thanks and regards

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 9 Jun 2006
Article Copyright 2006 by Malik Nasir
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid