Click here to Skip to main content
Licence 
First Posted 25 Oct 2004
Views 86,256
Bookmarked 54 times

Easier Database Transactions - Extending the Using Statement to Perform Automatic Database Transactions

By | 25 Oct 2004 | Article
Any user who works with database updates uses transactions. Transactions in ADO.NET are done using a transaction object, and a try..catch, but there is an easier, one might even say a more C# way to handle database transactions.
 
Part of The SQL Zone sponsored by
See Also

Overview

Any user who works with database updates uses transactions. Transactions in ADO.NET are done using a transaction object, and a try..catch, but there is an easier, one might even say a more C# way to handle database transactions.

Visual Basic .NET Users

Because this technique relies on the using statement which is C# specific, this technique cannot be applied in Visual Basic .NET. However, rumors are that Visual Studio .NET 2005 will include a similar statement for Visual Basic.

Transactions the Normal Way

Here is an example of a database transaction the normal way. This is a condensed version of the example on MSDN.

using (OleDbTransaction xTx = _DB.BeginTransaction()) {
    try {
        OleDbCommand xCmd = _DB.CreateCommand();
        xCmd.Transaction = xTx;
        xCmd.CommandText = "Insert into Person (Name, Telephone)" + 
                           " values ('Normal One', '(412) 555-1212')";
        xCmd.ExecuteNonQuery();
        if (chckThrow.Checked) {
            throw new Exception("Test Exception");
        }
        xCmd.CommandText = "Insert into Person (Name, Telephone)" + 
                           " values ('Normal Two', '(423) 555-1212')";
        xCmd.ExecuteNonQuery();
        xTx.Commit();
    }
    catch (Exception xException) {
        xTx.Rollback();
        throw xException;
    }
}

Transactions the Easy Way

With my method, the code does the same, but becomes a bit shorter, cleaner, and even a bit more C# like.

using (Transaction xTx = new Transaction(_DB)) {
    OleDbCommand xCmd = _DB.CreateCommand();
    ((IDbCommand)xCmd).Transaction = xTx.DBTransaction;
    xCmd.CommandText = "Insert into Person (Name, Telephone)" + 
                       " values ('Object One', '(412) 555-1212')";
    xCmd.ExecuteNonQuery();
    if (chckThrow.Checked) {
        throw new Exception("Test Exception");
    }
    xCmd.CommandText = "Insert into Person (Name, Telephone)" + 
                       " values ('Object Two', '(423) 555-1212')";    
    xCmd.ExecuteNonQuery();
    xTx.Commit();
}

Demo Project

The demo project demonstrates this and allows simulated exceptions. The demo project uses the included Access database file for simplicity. However, the included class works with any ADO.NET data source.

How it Works

The using statement in C# causes the dispose to be called when the block is exited. By implementing a Dispose, and checking to see if the transaction has been committed, the transaction class can then determine whether or not to call rollback. There is no need to rethrow any exception that may be in progress, because C# automatically continues the exception path as part of the handling of the using block.

Transaction Class Source

public class Transaction : IDisposable {

    private IDbConnection _DB;
    private IDbTransaction _DBTransaction;

    public IDbTransaction DBTransaction {
      get { return _DBTransaction; }
    }

    public Transaction(IDbConnection aDB) : this(aDB, true) {
    }

    public Transaction(IDbConnection aDB, bool aHandle) {
      if (aHandle) {
        _DB = aDB;
        _DBTransaction = _DB.BeginTransaction();
      }
    }

    public void Commit() {
      if (_DB != null) {
        _DBTransaction.Commit();
        _DBTransaction.Dispose();
        _DB = null;
      }
    }

    public void Dispose() {
      if (_DB != null) {
        _DBTransaction.Rollback();
        _DBTransaction.Dispose();
        _DB = null;
      }
    }
}

Conclusion

This class purely adds syntactic sugar to your code and makes performing transactions a little bit easier. The functionality is the same. But when working with transactions and having to manually create this structure each time, the shorter version is a lot easier to type, as well as read later when working in the code again.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Chad Z. Hower aka Kudzu

Other

Cyprus Cyprus

Member

Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
Website: http://www.KudzuWorld.com
Blogspace: http://www.KudzuWorld.com/blogs/
Speaking Profile: http://www.woo-hoo.net/
 
Formerly the Regional Developer Adviser (DPE) for Microsoft MEA (Middle East and Africa), he was responsible for 85 countries spanning 4 continents and crossing 10 time zones. Now Chad is Microsoft MVP and a professional speaker at popular developer conferences worldwide. Chad was once introduced as having "mastered more languages than a United Nations translator." Chad is the author of the book Indy in Depth and has contributed to several other books on network communications and general programming. Chad has lived in Canada, Cyprus, Switzerland, France, Jordan, Russia, Turkey, and the United States. In total Chad has visited more than 50 countries, visiting most of them many times.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralDifferent implementation of the transaction [modified] PinmemberPIEBALDconsult11:26 17 Mar '08  
GeneralRe: Different implementation of the transaction PinmemberChad Z. Hower aka Kudzu13:31 17 Mar '08  
I wrote this article when .NET 1.1 was current, IIRC that interface did not exist then. In .NET 2.0 a LOT of data classes got much needed interfaces as some were missing in 1.1.
 
Also since 2.0, there is a whole methodology of transactions built into .NET.
 
Chad Z. Hower, a.k.a. Kudzu
"Programming is an art form that fights back"
 
My Technical Stuff:
http://www.KudzuWorld.com
 
My Blogs:
http://www.KudzuWorld.com/blogs/

QuestionClose? PinsussAnonymous12:39 31 Oct '04  
AnswerRe: Close? PinmemberChad Z. Hower aka Kudzu14:12 31 Oct '04  
AnswerRe: Close? PinmemberAlvaro Mendez9:50 27 May '05  
GeneralNo need to wrap to shorten the code PinsussCandan Akyol9:46 26 Oct '04  
GeneralRe: No need to wrap to shorten the code PinmemberChad Z. Hower aka Kudzu2:18 27 Oct '04  
GeneralThe pattern is almost right... PinmembercasperOne3:06 26 Oct '04  
GeneralRe: The pattern is almost right... PinmemberChad Z. Hower aka Kudzu2:42 27 Oct '04  
QuestionIs shorter always better? PinmemberMark Focas12:13 25 Oct '04  
AnswerRe: Is shorter always better? PinmemberChad Z. Hower aka Kudzu12:25 25 Oct '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 25 Oct 2004
Article Copyright 2004 by Chad Z. Hower aka Kudzu
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid