Tuesday, June 26, 2007

Implementing Transactions in C#.Net

System.Data.SqlClient.SqlConnection sqlCon;
System.Data.SqlClient.SqlTransaction sqlTran;


save()
{
try
{
sqlCon = new SqlConnection(CommonFunctions.connectionString);
sqlCon.Open();
sqlTran = sqlCon.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
//----------------------------

//----------------------------
// Insertion code
// While inserting use sqlTran in place of normal connection string.
//----------------------------

//----------------------------
sqlTran.Commit();
}
catch(SqlException sqlEx)
{
sqlTran.Rollback();
throw new Exception(sqlEx.Message, sqlEx.InnerException);
}
catch(Exception SaveEx)
{
throw new Exception(SaveEx.Message, SaveEx.InnerException);
}
finally
{
sqlTran.Dispose();
sqlCon.Dispose();
}

}

No comments: