Transactions over multiple databases

by Dominic Zukiewicz 21. August 2007 11:57
Updating multiple databases (maybe on different servers), but in a "all-or-nothing" fashion. Its something that you will come across at least once in your professional career. But how do you do it in .NET?

Transactions work great if there's just one connection to one database at a time. But what happens if you want to update several databases? Microsoft thought of that too, using something called DTC (Distributed Transaction Co-ordinator). But that's in the COM/COM+ world and we don't want to touch that do we?? No! is the answer.

Digging through the documentation (or Google :-P) you can pick up a class called TransactionScope. TransactionScope is like a wrapper for any connections you wish to make to multiple databases. The beauty of this class is that it will even work across database implementations - e.g. Access, SQL and Oracle.

So if you were updating 3 databases, all in totally different formats and on different servers, this class will take care of it for you.

Here is a quick example of this:

using(TransactionScope tc = new TransactionScope())
{     
    using(SqlConnection sqlConn1 = ......)     
    {          
        using(SqlCommand comm) ....... 
        {
        }
     }
 
     using(OleDbConnection oleDbConn2 = ......)     
    {          
        using(OleDbCommand comm .......){}     
    }     
 
    using(OdbcConnection odbcConn3 = ......)     
    {          
        using(OdbcCommand comm.....)  {}     
    }     
 
    tc.Complete();
}


The entries are committed when, and on when, the .Complete() method is called. If it is disposed of before this call, no changes are made to any of the databases.

Here is a link to a presentation release by Microsoft on the TransactionScope class

Tags:

Framework

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar