I need to add transactions for a sql statement in a database application, up to this point, I have not need to do this, as I was primarily pulling data, or doing very small changes to existing data.
I have been using a tidy construct quite successfully with nested using statements, but I want to check with people who know better than me if this modified construct will work as I expect with the transaction embedded.
using (SqlCommand cmd = new SqlCommand())
using (cmd.Connection = new SqlConnection()) {
cmd.Connection.ConnectionString = "...";
cmd.Connection.Open();
using (SqlTransaction tran = cmd.Connection.BeginTransaction()) {
// do the work (try catch wraps the statements)
// commit transaction if no errors found or rollback
}
cmd.Connection.Close();
}
Thank you in advance
Regards
Martin
There is a built in class
TransactionScopethat is easier to use. Instantiate it in ausingblock and anything inside it will be part of the same transaction.If any exceptions occurs, the transactionscope will automatically abort all operations when disposed. The transactionscope also affects any operations done in any function called, without the need to pass db connections around.