Neither of those two methods is good. They are too verbose.
The best method is to just put the Transaction
in a using
as well, also we should use a parameter for the query:
using(var connection = new SqlConnection(connString))
using(var cmd = new SqlCommand("Insert into Customers (Name) values (@Name));"))
{
var param = cmd.Parameters.Add("@Name", SqlDbType.VarChar, insert_column_length_here);
connection.Open();
using(var transaction = connection.BeginTransaction())
{
cmd.Transaction = transaction;
param.Value = "Dimitri";
cmd.ExecuteNonQuery();
param.Value = "George";
cmd.ExecuteNonQuery();
transaction.Commit();
}
}
We can see that disposing the transaction object will automatically rollback if not already committed, by looking at the source code. So using
will clean everything up.
If you need to catch to display a message to the user, do it outside the code i.e. put a try/catch
around the whole thing. Don't do the cleanup code yourself
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…