Applying Cached Updates with Dataset Component Methods

From RAD Studio
Jump to: navigation, search

Go Up to Using the BDE to cache updates Index

Note: The Borland Database Engine (BDE) has been deprecated, so it will not be enhanced. For instance, BDE will never have Unicode support. You should not undertake new development with BDE. Consider migrating your existing database applications from BDE to dbExpress.

You can apply updates for individual BDE-enabled datasets directly using the dataset's ApplyUpdates and CommitUpdates methods. Each of these methods encapsulate one phase of the update process:

  1. ApplyUpdates writes cached changes to a database (phase 1).
  2. CommitUpdates clears the internal cache when the database write is successful (phase 2).

The following code illustrates how you apply updates within a transaction for the CustomerQuery dataset:

Delphi:

procedure TForm1.ApplyButtonClick(Sender: TObject)
begin
  Database1.StartTransaction;
  try
    if not (Database1.IsSQLBased) and not (Database1.TransIsolation = tiDirtyRead) then
      Database1.TransIsolation := tiDirtyRead;
    CustomerQuery.ApplyUpdates;                { try to write the updates to the database }
    Database1.Commit;                                    { on success, commit the changes }
  except
    Database1.Rollback;                                    { on failure, undo any changes }
    raise;                 { raise the exception again to prevent a call to CommitUpdates }
  end;
  CustomerQuery.CommitUpdates;                     { on success, clear the internal cache }
end;

C++:

void __fastcall TForm1::ApplyButtonClick(TObject *Sender)
{
  Database1->StartTransaction();
  try
  {
    if (!Database1->IsSQLBased && Database1->TransIsolation != tiDirtyRead)
      Database1->TransIsolation = tiDirtyRead;
    CustomerQuery->ApplyUpdates(); // try to write the updates to the database
    Database1->Commit(); // on success, commit the changes
  }
  catch (...)
  {
    Database1->Rollback(); // on failure, undo any changes
    throw; // throw the exception again to prevent a call to CommitUpdates
  }
  CustomerQuery->CommitUpdates(); // on success, clear the internal cache
}

If an exception is raised during the ApplyUpdates call, the database transaction is rolled back. Rolling back the transaction ensures that the underlying database table is not changed. The raise statement inside the try...except block reraises the exception, thereby preventing the call to CommitUpdates. Because CommitUpdates is not called, the internal cache of updates is not cleared so that you can handle error conditions and possibly retry the update.

See Also