private void TRANSACTION EXAMPLE(int example)
{
using (SqlConnection conn = new SqlConnection(dsn))
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
SqlTransaction transaction;
transaction = conn.BeginTransaction("GiveItAName");
cmd.Connection = conn;
cmd.Transaction = transaction;
try
{
//1st query, initializes sql variable
string sql = "INSERT INTO someTable etcetc";
cmd.CommandText = sql;
//define needed parameters is any
cmd.ExecuteNonQuery();
//next query
sql = "UPDATE or WHATEVER QUERY etc etc";
cmd.CommandText = sql;
// define needed parameters
// NOTE you don't have to define any param if it was already defines and used for a previous query
cmd.Parameters.Add("@something", SqlDbType.VarChar, 50).Value = exaple;
cmd.ExecuteNonQuery();
//next query
sql = "UPDATE etc etc";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
}
catch (Exception)
{
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
throw;
}
throw;
}
}
}
Tuesday, April 1, 2008
transaction
I am always looking through our code for a previous example of using transactions in .NET, so I am posting the code here. That's what here is for!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment