Transaction Facts
A transaction is a group of related tasks that are treated as a single unit. By using transactions, you can ensure that all tasks must complete successfully before any of the changes are made. For example, you might have a bank transaction that transfers money from one account to another. This transaction is composed of two separate steps (performed in this order):
- Take money from one account (debit)
- Deposit the money into another account (credit/deposit)
Using transactions, if the deposit fails, the debit from the original account can be rolled back (no changes are saved).
You can include transactions in your code using the following steps:
- Configure Connection and Command objects.
- Instantiate a Transaction object. Transaction objects are data source specific.
- Call the BeginTransaction method.
- Link the Transaction to the Command.
- Perform the database operations that are part of the transaction.
- If all tasks complete successfully, call the Commit method to make the changes. If there was an error, call the Rollback method to remove those changes.
The following example shows using a SqlTransaction.
// The following example assumes the following objects:
// SqlConnection called myConn
// SqlCommand called myComm
// Open the connection
myConn.Open();
// Instantiate and begin the Transaction
SqlTransaction myTrans;
myTrans = myComm.BeginTransaction();
// Associate the Connection and Transaction with
// the Command
myComm.Connection = myConn;
myComm.Transaction = myTrans;
try
{
// Execute commands here such as setting the
// command text and executing commands
// Commit the changes
myTrans.Commit();
}
// If an error occurred, rollback changes
catch (Exception e)
{
myTrans.Rollback();
}
// Close the connection
finally
{
myConn.Close();
}
Digg it | Save to del.icio.us | Netscape | Reddit | Stumble It!
- - - - - S P O N S O R I N G A D V E R T I S M E N T - - - - -