Home > Code > C# > Creating ADO.NET Transactions

Creating ADO.NET Transactions

by Narain Siddharth   on Nov 13, 2010   Category: C#   |  Views: 1285    |  Points: 25   |  Silver 


See the below sample code for ADO.NET Transactions

using System;
using System.Data;
using System.Data.SqlClient;

namespace TranExample
{

class TransactionExample
{
static void Main(string[] args)
{
SqlTransaction objtrans = null;
SqlConnection objconn = null;
SqlCommand objcomm = null;
try
{
objconn = new SqlConnection("Your connection string");
objconn.Open();
objcomm = objconn.CreateCommand();
objtrans = objconn.BeginTransaction("TestTransaction");
objcomm.Connection = objconn;
objcomm.Transaction = objtrans;
objcomm.CommandText = "Your SQL Query";
objcomm.ExecuteNonQuery();
objcomm.CommandText = " Your SQL Query";
objcomm.ExecuteNonQuery();
objtrans.Commit();
}
catch(Exception e)
{
try
{
if (objtrans != null)
{
objtrans.Rollback("TestTransaction ");
}
}
catch (SqlException ex)
{
If (objtrans.Connection != null)
{
Console.WriteLine("Error" + ex.GetType() + " occurred while rolling back the Database transaction.");
}
}
Console.WriteLine("Error " + e.GetType() + " occurred while executing the query.");
}
finally
{
If (objconn != null)
{
objconn.Close();
}
}
}
}
}


If you find the above code useful, please leave your comments.



Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts