bboks.net™

C# 트랜잭션 처리 본문

C# | ASP.NET/C#

C# 트랜잭션 처리

bboks.net 2010. 8. 5. 09:45
public void TransactionExample()
{
    private const string CONNECT_STR = "server=server_ip;database=db_name;user id=user_id;password=password;";
    
    private SqlConnection con = new SqlConnection(CONNECT_STR);;
    private SqlCommand cmd = new SqlCommand();

    command.Connection = con;

    try
    {
        con.Open();

        //트랜잭션 시작
        cmd.Transaction = cmd.Connection.BeginTransaction();

        //쿼리 지정
        cmd.CommandText = "Update ... SET ....";
        cmd.Parameters.Clear();

        //쿼리 실행
        cmd.ExecuteNonQuery();

        //트랜잭션 Commit
        cmd.Transaction.Commit();
    }
    catch (Exception ex)
    {
        if (cmd.Transaction != null)
        {
            //오류 발생시 Rollback
            cmd.Transaction.Rollback();
        }

        Console.WriteLine("ERROR : " + ex.Source + " - " + ex.Message);
    }
}