Wednesday, September 7, 2011

Transaction in C# with Sql-Server Code behind







using System;
using System.Data.SqlClient;

namespace CsharpWebApp
{
    public class TransactionDemo
    {
        public TransactionDemo()
        {

        }

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

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

            dbConn.Open();
            transaction = dbConn.BeginTransaction();

            SqlCommand sqlDept = new SqlCommand("INSERT INTO EmployeeDepartment (EmpId, Department) VALUES (1,

'Department');", dbConn, transaction);
            SqlCommand sqlManager = new SqlCommand("INSERT INTO EmployeeManager (EmpId, Manager) VALUES (1,

'Department');", dbConn, transaction);

            try
            {
                sqlDept.ExecuteNonQuery();
                sqlManager.ExecuteNonQuery();
                transaction.Commit();
            }
            catch (SqlException sqlError)
            {
                transaction.Rollback();
            }
            finally
            {
                dbConn.Close();
                sqlDept.Dispose();
                sqlManager.Dispose();
                dbConn.Dispose();
            }
          
        }
    }

No comments:

Post a Comment

Implementing Service Locator (To Resolve Dependency)

using System; /// <summary> /// Summary description for Class1 /// </summary> public class serviceLocator {     public s...