프로그램/C# - Study / / 2010. 10. 18. 10:49

C# - EX04 SqlTransaction, TransactionScope 활용

반응형

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Transactions;

namespace Ex04
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.Local Transaction
            //------------------------------------------------------------------------
            //SqlConnection conn = new SqlConnection();
            //conn.ConnectionString = "SERVER=.;" +
            //                        "DATABASE=exampledb;" +
            //                        "UID=sa;PWD=knit";


            //SqlCommand cmd = new SqlCommand();
            //cmd.Connection = conn;

            ////동일 데이터베이스의 두 개 이상의 명령에 대한 트랜잭션
            ////Transaction 객체를 사용해서 트랜잭션 관리
            //SqlTransaction tran = null;  // 롤백을 하기 위해 추가
            //try
            //{
            //    conn.Open();
            //    tran = conn.BeginTransaction();  // 롤백을 하기 위해 추가
            //    cmd.Transaction = tran;  // 롤백을 하기 위해 추가

            //    cmd.CommandText = "UPDATE bankaccount " +
            //                      "SET balance = balance - 500 " +
            //                      "WHERE ac_owner = '장동건'";
            //    cmd.ExecuteNonQuery();

            //    cmd.CommandText = "UPDATE bankaccount " +
            //                      "SET balance222 = balance + 500 " +
            //                      "WHERE ac_owner = '김윤석'";
            //    cmd.ExecuteNonQuery();
            //    tran.Commit(); // 롤백을 하기 위해 추가
            //    Console.WriteLine("계좌이체 성공");
            //}
            //catch(Exception)
            //{
            //    tran.Rollback();  // 롤백을 하기 위해 추가
            //    Console.WriteLine("계좌이체 실패");
            //}
            //finally { conn.Close(); }

            //-----------------------------------------------------------------------------
            //2. Distributed Transaction
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString =
                "SERVER=.;" +
                "DATABASE=exampledb;" +
                "UID=sa;PWD=knit;";

            SqlConnection conn2 = new SqlConnection();
            conn2.ConnectionString =
                "SERVER=172.16.7.1;" +
                "DATABASE=exampledb;" +
                "UID=sa;PWD=knit;";

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;

            SqlCommand cmd2 = new SqlCommand();
            cmd2.Connection = conn2;
            //참조 추가 System.Transactions 추가
            //start distributed transaction
            TransactionScope scope = new TransactionScope(); ;

            try
            {
                conn.Open();
                conn2.Open();

                cmd.CommandText =
                    "UPDATE bankaccount " +
                    "SET balance = balance + 500 " +
                    "WHERE ac_owner = '장동건'";
                cmd.ExecuteNonQuery();
                cmd2.CommandText =
                    "UPDATE bankaccount " +
                    "SET balance = balance + 9500 " +
                    "WHERE ac_owner = '김윤석'";
                cmd2.ExecuteNonQuery();

                scope.Complete(); //성공 표시 (commit X)
                Console.WriteLine("계좌이체 성공");
            }
            catch (Exception ex)
            {
                Console.WriteLine("계좌이체 실패");
                Console.WriteLine(ex.Message);
            }
            finally { conn.Close(); conn2.Close(); }

            //Complete()이 호출 되었으면 Commit 아니면 Rollback
            scope.Dispose();
        }
    }
}
////////////////////////////////////////////////////////////////////
// 과제
// 연락처관리 프로그램 & 윈폼 기반 DB 사용
// 등록 & 수정 & 삭제 & 목록 보기 & 검색( 와일드 카드 검색 (이름%)으로 )
////////////////////////////////////////////////////////////////////

반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유