Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In line with this post here I am going to change my website to create a connection per query to take advantage of .NET's connection pooling. With this in mind, I don't know how I should deal with transactions. At the moment I do something like (psuedo code):

GlobalTransaction = GlobalDBConnection.BeginTransaction();
    ExecSQL("insert into table ..")
    ExecSQL("update some_table ..")

ExecSQL would be like this:

using (SqlCommand Command = GlobalDBConnection.CreateCommand())
    Command.Connection = GlobalDBConnection;
    Command.Transaction = GlobalTransaction;
    Command.CommandText = SQLStr;

I'm not quite sure how to change this concept to deal with transactions if the connection is created within ExecSQL because I would want the transaction to be shared between both the insert and update routines.

share|improve this question
up vote 4 down vote accepted

You should be using TransactionScope for transactions in .NET:

using(var tx = new TransactionScope())
    ExecSQL("insert into table ..")
    ExecSQL("update some_table ..")

The above code will ensure both statements will belong to one transaction.

You can nest TransactionScopes if needed.

share|improve this answer
Perfect. Many thanks Oded. – webnoob Mar 29 '12 at 11:11
Just keep in mind that transactions will escalate to a distributed transaction if you are connecting to different data sources. MS DTC (Microsoft Distributed Transaction Coordinator) would then be needed to facilitate those types of scenarios. – Jon Raynor Mar 29 '12 at 19:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.