Transaction in ADO.Net

The Code Snippet Demonstrates How Simple Transaction Works.




// Connection to your database using SQLConnection Object,Lets say SQLConnection Object name is sqlcon

SQLCommand sqlCom = sqlcon.CreateCommand();
SQLTransaction sqlTran;

// Start a local transaction

sqlTran = salcon.BeginTransaction();

/* Assign Both transaction object and connection to Command Object for pending local transaction */

sqlCom.Connection = sqlCon;
sqlCom.Transaction = sqlTran;

try
{
sqlCom.CommandText = "Insert or Update or Delete Command as per sql Syntax";
sqlCom.ExecuteNonQuery();

// Trying to Commit the Transaction

sqlTran.Commit();
MessageBox.Show("Records Are Written To Database....");

}
catch(Exception objException1)
{

MessageBox.Show("Commit Exception Occured :" + objException1.GetType());

// Trying to Rollback the Transaction

try
{
sqlTran.RollBack();
}
catch(Exception objException2)
{
MessageBox.Show("RollBack Exception Occured :" + objException2.GetType());
}


}


Comments

Author: Spidy04 Nov 2009 Member Level: Gold   Points : 0

Good Info..
Keep Posting.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: