Monday, October 25, 2010

Handling DatabaseTransactions


Transaction is a unit of work, when completed, takes the database from one stage to another.

This post assumes the database to be MySQL and it is almost same in other databases too. 


You will have 3 steps to do:

You need to begin a transaction, code required statements and end the transaction.

Step 1: Start the transaction: Initiate a transaction by using BEGIN WORK command. When you issue this command, MySQL assumes that everything following it is part of a transaction

BEGIN WORK;

You can also use just BEGIN, or use the equivalent START TRANSACTION command.

Step 2: Perform the transaction

Once the transaction is start, use SQL commands as necessary. The dirty data visibility to other processes depends on the isolation level set for the database. 


Step 3: End the transaction
Once done with the SQL commands, you can either cancel the transaction or save the transaction to database.

To cancel the transaction, use ROLLBACK command. It means when we issue ROLLBACK command, the database will go to the state before the BEGIN WORK command has been issued.

To save the transaction, use COMMIT command. This statement will save all the changes to database done with the previous SQL commands.

We also have a AUTOCOMMIT feature, which implicitly saves the changes. But do a research before setting it to ON/OFF.
Source: http://www.weberdev.com/ViewArticle/Using-Transactions-In-MySQL-Part-1
This article copyright Melonfire, 2005. All rights reserved.