Using Delphi Firedac to compact and repair a MS Access Database.

Over the years Delphi Firedac continues to grow as a robust programming language. Delphi Firedac provides a new way to compact and repair a database.

The tools provide developers with components or services that create superb applications.

Delphi Firedac provides a unique set of Universal Data Access Components for developing multi-device database applications.

This will show the older method of compacting and repairing MS Access databases.

The code listed below demonstrates the process. Very straight forward you need to create the object, populate the commands and you are ready to go.

function CompactAndRepair(DB: string): Boolean;
var
  v: OLEvariant;
begin
  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+'compacted;Jet OLEDB:Engine Type=5');
      DeleteFile(DB);
      RenameFile(DB+'compacted',DB);
    finally
      V := Unassigned;
    end;
  except
    Result := False;
  end;
end;
Baron Software

Delphi Firedac now has a cleaner way of executing these functions with a few lines.

In your data module you need to drop a FDMSAccessService component and set the driver link to FDPhysMSAccessDriverLink

The database connection should be close.

The database name and path should be set.

The database password needs to be set only if you use one.

Execute a repair and a compact to complete the task.

function TfrmMainForm.CompactAndRepair(const DB: string): Boolean;
begin
  Result := True;
  DM.DataMod.FDConnection.Connected := False;
  DM.DataMod.FDMSAccessService.Database := DB;
  DM.DataMod.FDMSAccessService.Password := 'PASSWORD';
try
     DM.DataMod.FDMSAccessService.Repair;
  except
     on E : Exception do
     begin
       ShowMessage('Exception message = '+E.Message);
       Result := False;
     end;
  end;

  try
      DM.DataMod.FDMSAccessService.Compact;
  except
     on E : Exception do
     begin
       ShowMessage('Exception message = '+E.Message);
       Result := False;
     end;
  end;
  DM.DataMod.FDConnection.Connected := True;

end;

Using Delphi Firedac makes the process quick and clean. You can visit the Embarcadero web site for Delphi Firedac database support.