Icon Executing Transactions

A transaction is executed entirely by using the StartTransaction, Commit, and Rollback methods of the TEDBDatabase component. A typical transaction block of code looks like this:

begin
   with MyDatabase do
      begin
      StartTransaction(EmptyEDBStringsArray);
      try
         { Perform some updates to the table(s) in this database }
         Commit;
      except
         Rollback;
      end;
      end;
end;

The EmptyEDBStringsArray variable is defined in the edbtype unit (Delphi or Lazarus) or edbtype header file (C++) in ElevateDB.

Information It is very important that you always ensure that the transaction is rolled back if there is an exception of any kind during the transaction. This will ensure that the locks held by the transaction are released and other sessions can continue to update data while the exception is dealt with. Also, if you roll back a transaction it is always a good idea to refresh any open TEDBTable or TEDBQuery components linked to the TEDBDatabase component involved in the transaction so that they reflect the current data and not any data from the transaction that was just rolled back. Along with refreshing, you should make sure that any pending inserts or edits for the TEDBTable or TEDBQuery components are cancelled using the Cancel method before the transaction is rolled back to ensure that the inserts or edits are not accidentally posted using the Post method after the transaction is rolled back (unless that is specifically what you wish to do).

Restricted Transactions
It is also possible with ElevateDB to start a restricted transaction. A restricted transaction is one that specifies only certain tables be part of the transaction. The StartTransaction method accepts an optional array of tables that can be used to specify what tables should be involved in the transaction and, subsequently, locked as part of the transaction (see below regarding locking). If this list of tables is nil (the default), then the transaction will encompass the entire database.

The following example shows how to use a restricted transaction on two tables, the Customer and Orders table:

var
   Tables: TEDBStringsArray;
begin
   with MyDatabase do
      begin
      SetLength(Tables,2);
      Tables[0]:='Customer';
      Tables[1]:='Orders';
      StartTransaction(Tables);
      try
         { Perform some updates to the table(s) in the transaction }
         Commit;
      except
         Rollback;
         raise;
      end;
      end;
end;

For more information on transactions in ElevateDB, please see the Transactions topic.
Image