Using a Transaction Component

From InterBase
Jump to: navigation, search

Go Up to Using Transactions


When you start a transaction, all subsequent statements that read from and write to the database occur in the context of that transaction. Each statement is considered part of a group. Changes must be successfully committed to the database, or every change made in the group must be undone.

Ideally, a transaction should only last as long as necessary. The longer a transaction is active, the more simultaneous users that access the database, and the more concurrent, simultaneous transactions that start and end during the lifetime of your transaction, the greater the likelihood that your transaction will conflict with another when you attempt to commit your changes.

When using a transaction component, you code a single transaction as follows:

  1. Start the transaction by calling the transaction’s StartTransaction method:
    IBTransaction.StartTransaction;
    
  2. Once the transaction is started, all subsequent database actions are considered part of the transaction until the transaction is explicitly terminated. You can determine whether a transaction is in process by checking the transaction component’s InTransaction property.
  3. When the actions that make up the transaction have all succeeded, you can make the database changes permanent by using the transaction component’s Commit method:
    IBTransaction.Commit;
    

    Alternately, you can commit the transaction while retaining the current transaction context using the CommitRetaining method:

      IBTransaction.CommitRetaining;
    

    Commit is usually attempted in a try...except statement. That way, if a transaction cannot commit successfully, you can use the except block to handle the error and retry the operation or to roll back the transaction.

    If an error occurs when making the changes that are part of the transaction, or when trying to commit the transaction, you will want to discard all changes that make up the transaction. To discard these changes, use the database component’s Rollback method:

    IBTransaction.Rollback;
    

    You can also rollback the transaction while retaining the current transaction context using the RollbackRetaining method:

       IBTransaction.RollbackRetaining;
    

    Rollback usually occurs in

    • Exception handling code when you cannot recover from a database error.
    • Button or menu event code, such as when a user clicks a Cancel button.