Friday, February 3, 2012

Transaction Management using ADO .Net with example

 "Dot Net Implementation code with example for Transaction Management"

I discussed the basic details of transaction as why and when we use transactions and how to implement them, I shared it all in my previous post. If still you don't have the basic info then you can read from here.
 
Now I want to tell you the process of transaction management using ADO .Net

Within .NET, transactions are managed with the System.Data.SqlClient.SqlTransaction class. Again, a transaction exists over a SqlConnection object – and thus all the SqlCommand objects you create using that connection. Let's look at a quick example:

                         "Have a look at this example" 
public class TransactionDemo
{
   public TransactionDemo()
   {

   }

   [STAThread]
   public static void Main() 
   {
      Demo1();
   }

   private static void Demo1() 
   {
      SqlConnection dbConn = new SqlConnection("connstringhere");
      SqlTransaction transaction;

      dbConn.Open();
      transaction = dbConn.BeginTransaction();
      try 
      {
         new SqlCommand("INSERT INTO TransactionDemo " +
            "(Text) VALUES ('Row1');",dbConn,transaction)
            .ExecuteNonQuery();
         new SqlCommand("INSERT INTO TransactionDemo " +
            "(Text) VALUES ('Row2');", dbConn, transaction)
            .ExecuteNonQuery();
         new SqlCommand("INSERT INTO CrashMeNow VALUES " +
            "('Die', 'Die', 'Die');", dbConn, transaction)
            .ExecuteNonQuery();
         transaction.Commit();
      } 
      catch (SqlException sqlError) 
      {
         transaction.Rollback();
      }
      db.Close();
   }
}

0 comments:

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Powered by Code Imagine