2

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();
try
{
 ExecSQL("insert into table ..")
 ExecSQL("update some_table ..")
 ....
 GlobalTransaction.Commit();
}catch{
 GlobalTransaction.Rollback();
 throw;
}

ExecSQL would be like this:

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

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.

asked Mar 29, 2012 at 11:02

1 Answer 1

4

You should be using TransactionScope for transactions in .NET:

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

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

You can nest TransactionScopes if needed.

answered Mar 29, 2012 at 11:06
1
  • 1
    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. Commented Mar 29, 2012 at 19:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.