Using a database component for 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 database component, you code a single transaction as follows:

1.Start the transaction by calling the database’s StartTransaction method.

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 database component’s InTransaction property. While the transaction is in process, your view of the data in database tables is determined by you transaction isolation level.
3.When the actions that make up the transaction have all succeeded, you can make the database changes permanent by using the database component’s Commit method.

Commit is usually attempted in a try...catch statement. That way, if a transaction cannot commit successfully, you can use the catch block to handle the error and retry the operation or to roll back the transaction.
4If 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.

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.

Comments

Popular posts from this blog

TClientDataSet::AppendData and TClientDataSet::BeforeGetRecords

OleVariant

cdecl, _cdecl, __cdecl