JabbaTheNut
Programmer
Are there any potential problems with assigning the same transaction to multiple commands? I want to execute a few commands. However, if any one of them fails, I want to rollback everything. The following code illustrates what I want to do (Note that I am assigning the same transaction to both commands):
SqlConnection myConnection = new SqlConnection(myConnString);
myConnection.Open();
SqlCommand myCommand1 = myConnection.CreateCommand();
SqlCommand myCommand2 = myConnection.CreateCommand();
SqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Assign both the transaction object and the connection
// to the Command objects for the pending local transaction
myCommand1.Connection = myConnection;
myCommand1.Transaction = myTrans;
myCommand2.Connection = myConnection;
myCommand2.Transaction = myTrans;
try
{
myCommand1.CommandText = "Do Something";
myCommand1.ExecuteNonQuery();
myCommand2.CommandText = "Do Something Else";
myCommand2.ExecuteNonQuery();
myTrans.Commit();
}
catch(Exception e)
{
myTrans.Rollback();
}
finally
{
myConnection.Close();
}
Game Over, Man!
SqlConnection myConnection = new SqlConnection(myConnString);
myConnection.Open();
SqlCommand myCommand1 = myConnection.CreateCommand();
SqlCommand myCommand2 = myConnection.CreateCommand();
SqlTransaction myTrans;
// Start a local transaction
myTrans = myConnection.BeginTransaction();
// Assign both the transaction object and the connection
// to the Command objects for the pending local transaction
myCommand1.Connection = myConnection;
myCommand1.Transaction = myTrans;
myCommand2.Connection = myConnection;
myCommand2.Transaction = myTrans;
try
{
myCommand1.CommandText = "Do Something";
myCommand1.ExecuteNonQuery();
myCommand2.CommandText = "Do Something Else";
myCommand2.ExecuteNonQuery();
myTrans.Commit();
}
catch(Exception e)
{
myTrans.Rollback();
}
finally
{
myConnection.Close();
}
Game Over, Man!