Wednesday, May 16, 2007

ADO.Net Transaction Object

A Transaction is an atomic unit of work that must be completed in its entirety. The transaction succeeds if it is committed and otherwise fails if it is aborted.

Essential properties of transactions (ACID):
  • Atomicity - work cannot be broken into smaller parts.
  • Consistency - data must always be consistent.
  • Isolation - the transaction should be running by itself and should not be affected nor affect other transactions.
  • Durability - committed transactions should always be persisted.

ex:

using (SqlConnection cn = new SqlConnection()) {
cn.ConnectionString = "CONNECTION STRING HERE!";
cn.Open();
using (SqlTransaction tran = cn.BeginTransaction()) {
try {

using (SqlCommand cmd = cn.CreateCommand()) {
cmd.Transaction = tran;
cmd.CommandText = "SQL TEXT HERE!";
// SQL EXECUTE HERE!
}
tran.Commit();
}
catch (Exception xcp) {
tran.Rollback();
}
}
}

No comments: