Saturday 18 February 2012

transaction ACID property with c#


A transaction has specifi c requirements; for example, a transaction must result in a valid state, even if the
server has a power failure. The characteristics of transactions can be defi ned by the term ACID. ACID is a
four - letter acronym for atomicity, consistency, isolation, and durability :
➤ Atomicity — R epresents one unit of work. With a transaction, either the complete unit of work
succeeds or nothing is changed.
➤ Consistency — T he state before the transaction was started and after the transaction is completed
must be valid. During the transaction, the state may have interim values.
➤ Isolation — M eans that transactions that happen concurrently are isolated from the state, which is
changed during a transaction. Transaction A cannot see the interim state of transaction B until the
transaction is completed.
➤ Durability — A fter the transaction is completed, it must be stored in a durable way. This means that if
the power goes down or the server crashes, the state must be recovered at reboot.
Not every transaction requires all four ACID properties. For example, a memory - based transaction (for
example, writing an entry into a list) does not need to be durable. Also, a complete isolation from the
outside is not always required, as we discuss later with transaction isolation levels.


using System;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Wrox.ProCSharp.Transactions
{
public class CourseData
{
public void AddCourse(Course course)
{
var connection = new SqlConnection(
Properties.Settings.Default.CourseManagementConnectionString);
SqlCommand courseCommand = connection.CreateCommand();
courseCommand.CommandText =
"INSERT INTO Courses (Number, Title) VALUES (@Number, @Title)";
connection.Open();
SqlTransaction tx = connection.BeginTransaction();
try
{
courseCommand.Transaction = tx;
courseCommand.Parameters.AddWithValue("@Number", course.Number);
courseCommand.Parameters.AddWithValue("@Title", course.Title);
courseCommand.ExecuteNonQuery();
tx.Commit();
}
catch (Exception ex)
{Trace.WriteLine("Error: " + ex.Message);
tx.Rollback();
}
finally
{
connection.Close();
}
}
}
}

No comments:

Post a Comment