DelphiFAQ Home Search:

Compact and repair an Access database from Delphi

 

comments6 comments. Current rating: 5 stars (2 votes). Leave comments and/ or rate it.

Question:

I need to rebuild a Microsoft Access database from Delphi. How can I do this?

Answer:

The code below creates a JetEngine object and uses its CompactDatabase() method to save the compacted db under a new filename. Obviously it needs exclusive access for this. Afterwards the db files are swapped and available for everyone again.

uses
  ComObj;

// Compact and repair an access database, it requires exclusive db access.
// argument DB = Path to Access Database
function CompactAndRepair(DB: string) : boolean;
var
  v: OLEvariant;
begin { CompactAndRepair }
  Result := True;
  try
    v := CreateOLEObject('JRO.JetEngine');
    try
      v.CompactDatabase('Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + DB,
                        'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + DB +
                        'x;Jet OLEDB:Engine type=5');
      DeleteFile(DB);
      RenameFile(DB + 'x', DB)
    finally
      v := Unassigned
    end; { try }

  except
    Result := False
  end; { try }
end; { CompactAndRepair }
You don't like the formatting? Check out SourceCoder then!

Comments:

2006-01-13, 09:31:52
anonymous from Spain  
rating
2006-02-05, 15:09:07
xp0027 from Mexico  
rating
10x!!!!!!!
2006-09-25, 20:40:46
anonymous from Australia  
huh?
2007-10-05, 21:08:47
anonymous from Brazil  
Congratulation nice post
2008-04-18, 13:47:08
anonymous from Brazil  
Very good! Thank by help-me
2008-06-10, 03:47:40
anonymous  
Great Tool!

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: