SqlConnection.BeginTransaction 메서드

정의

데이터베이스 트랜잭션을 시작합니다.

오버로드

BeginTransaction()

데이터베이스 트랜잭션을 시작합니다.

BeginTransaction(IsolationLevel)

지정된 격리 수준으로 데이터베이스 트랜잭션을 시작합니다.

BeginTransaction(String)

지정된 트랜잭션 이름으로 데이터베이스 트랜잭션을 시작합니다.

BeginTransaction(IsolationLevel, String)

지정된 격리 수준과 트랜잭션 이름으로 데이터베이스 트랜잭션을 시작합니다.

BeginTransaction()

데이터베이스 트랜잭션을 시작합니다.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction();
public System.Data.SqlClient.SqlTransaction BeginTransaction ();
override this.BeginTransaction : unit -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : unit -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction () As SqlTransaction

반환

SqlTransaction

새 트랜잭션을 나타내는 개체입니다.

예외

MARS(Multiple Active Result Sets)를 사용하는 경우 병렬 트랜잭션은 허용되지 않습니다.

병렬 트랜잭션은 지원되지 않습니다.

예제

다음 예제에서는 a 및 .를 SqlConnection SqlTransaction만듭니다. 또한 , a 및 Rollback 메서드를 BeginTransactionCommit사용하는 방법을 보여 줍니다.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction();

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction()

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"

            command.ExecuteNonQuery()

            ' Attempt to commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType())
            Console.WriteLine("  Message: {0}", ex.Message)

            ' Attempt to roll back the transaction.
            Try
                transaction.Rollback()

            Catch ex2 As Exception
                ' This catch block will handle any errors that may have occurred
                ' on the server that would cause the rollback to fail, such as
                ' a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
                Console.WriteLine("  Message: {0}", ex2.Message)
            End Try
        End Try
    End Using
End Sub

설명

이 명령은 BEGIN TRANSACTION의 SQL Server 구현에 매핑됩니다.

또는 Rollback 메서드를 사용하여 Commit 트랜잭션을 명시적으로 커밋하거나 롤백해야 합니다. SQL Server 트랜잭션 관리 모델의 .NET Framework Data Provider 올바르게 수행되도록 하려면 SQL Server 제공된 모델과 같은 다른 트랜잭션 관리 모델을 사용하지 마십시오.

참고

격리 수준을 지정하지 않으면 기본 격리 수준이 사용됩니다. 메서드를 사용하여 격리 수준을 BeginTransaction 지정하려면 매개 변수(BeginTransaction)를 사용하는 오버로드를 iso 사용합니다. 트랜잭션에 대한 격리 수준 집합은 트랜잭션이 완료된 후 연결이 닫혀 있거나 삭제될 때까지 유지됩니다. 스냅샷 격리 수준을 사용하도록 설정하지 않은 데이터베이스에서 격리 수준을 스냅샷 으로 설정해도 예외가 발생하지 않습니다. 트랜잭션은 기본 격리 수준을 사용하여 완료됩니다.

주의

트랜잭션이 시작되고 서버에서 수준 16 이상의 오류가 발생하면 메서드가 호출될 때까지 Read 트랜잭션이 롤백되지 않습니다. ExecuteReader 에서 예외가 throw되지 않습니다.

주의

쿼리에서 대량의 데이터와 호출 BeginTransactionSqlException 을 반환하면 mars를 사용할 때 SQL Server 병렬 트랜잭션을 허용하지 않기 때문에 throw됩니다. 이 문제를 방지하려면 읽기 프로그램이 열리기 전에 항상 트랜잭션을 명령, 연결 또는 둘 다와 연결합니다.

SQL Server 트랜잭션에 대한 자세한 내용은 트랜잭션(Transact-SQL)을 참조하세요.

추가 정보

적용 대상

BeginTransaction(IsolationLevel)

지정된 격리 수준으로 데이터베이스 트랜잭션을 시작합니다.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso);
public System.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso);
override this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel) As SqlTransaction

매개 변수

iso
IsolationLevel

트랜잭션이 실행되어야 하는 격리 수준입니다.

반환

SqlTransaction

새 트랜잭션을 나타내는 개체입니다.

예외

MARS(Multiple Active Result Sets)를 사용하는 경우 병렬 트랜잭션은 허용되지 않습니다.

병렬 트랜잭션은 지원되지 않습니다.

예제

다음 예제에서는 a 및 .를 SqlConnection SqlTransaction만듭니다. 또한 , a 및 Rollback 메서드를 BeginTransactionCommit사용하는 방법을 보여 줍니다.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback();
            }
            catch (SqlException ex)
            {
                if (transaction.Connection != null)
                {
                    Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                }
            }

            Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
            Console.WriteLine("Neither record was written to database.");
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")
        Catch e As Exception
            Try
                transaction.Rollback()
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

설명

이 명령은 BEGIN TRANSACTION의 SQL Server 구현에 매핑됩니다.

또는 Rollback 메서드를 사용하여 Commit 트랜잭션을 명시적으로 커밋하거나 롤백해야 합니다. SQL Server 트랜잭션 관리 모델의 .NET Framework Data Provider 올바르게 수행되도록 하려면 SQL Server 제공된 모델과 같은 다른 트랜잭션 관리 모델을 사용하지 마십시오.

참고

트랜잭션이 커밋되거나 롤백된 후 트랜잭션의 격리 수준은 자동 커밋 모드(SQL Server 기본값)에 있는 모든 후속 명령에 대해 유지됩니다. 이렇게 하면 반복 가능한 읽기의 격리 수준 유지 및 다른 사용자를 행에서 잠그는 등의 예기치 않은 결과가 발생할 수 있습니다. 격리 수준을 기본값(READ COMMITTED)으로 다시 설정하려면 Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED 문을 실행하거나 즉시 SqlTransaction.Commit호출 SqlConnection.BeginTransaction 합니다. SQL Server 격리 수준에 대한 자세한 내용은 트랜잭션 격리 수준을 참조하세요.

SQL Server 트랜잭션에 대한 자세한 내용은 트랜잭션(Transact-SQL)을 참조하세요.

주의

쿼리에서 대량의 데이터와 호출 BeginTransactionSqlException 을 반환하면 mars를 사용할 때 SQL Server 병렬 트랜잭션을 허용하지 않기 때문에 throw됩니다. 이 문제를 방지하려면 읽기 프로그램이 열리기 전에 항상 트랜잭션을 명령, 연결 또는 둘 다와 연결합니다.

추가 정보

적용 대상

BeginTransaction(String)

지정된 트랜잭션 이름으로 데이터베이스 트랜잭션을 시작합니다.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction (string transactionName);
override this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (transactionName As String) As SqlTransaction

매개 변수

transactionName
String

트랜잭션 이름입니다.

반환

SqlTransaction

새 트랜잭션을 나타내는 개체입니다.

예외

MARS(Multiple Active Result Sets)를 사용하는 경우 병렬 트랜잭션은 허용되지 않습니다.

병렬 트랜잭션은 지원되지 않습니다.

예제

다음 예제에서는 a 및 .를 SqlConnection SqlTransaction만듭니다. 또한 , a 및 Rollback 메서드를 BeginTransactionCommit사용하는 방법을 보여 줍니다.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback("SampleTransaction");
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction("SampleTransaction")

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"

            command.ExecuteNonQuery()

            ' Attempt to commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine("Exception Type: {0}", ex.GetType())
            Console.WriteLine("  Message: {0}", ex.Message)

            ' Attempt to roll back the transaction.
            Try
                transaction.Rollback("SampleTransaction")

            Catch ex2 As Exception
                ' This catch block will handle any errors that may have occurred
                ' on the server that would cause the rollback to fail, such as
                ' a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
                Console.WriteLine("  Message: {0}", ex2.Message)
            End Try
        End Try
    End Using
End Sub

설명

이 명령은 BEGIN TRANSACTION의 SQL Server 구현에 매핑됩니다.

매개 변수의 transactionName 길이가 32자를 초과하면 안 됩니다. 그렇지 않으면 예외가 throw됩니다.

매개 변수의 값은 메서드의 transactionName 이후 호출 Rollback 및 매개 변수 Save 에서 savePoint 사용할 수 있습니다.

또는 Rollback 메서드를 사용하여 Commit 트랜잭션을 명시적으로 커밋하거나 롤백해야 합니다. SQL Server 트랜잭션 관리 모델의 .NET Framework Data Provider 올바르게 수행되도록 하려면 SQL Server 제공된 모델과 같은 다른 트랜잭션 관리 모델을 사용하지 마십시오.

SQL Server 트랜잭션에 대한 자세한 내용은 트랜잭션(Transact-SQL)을 참조하세요.

주의

쿼리에서 대량의 데이터와 호출 BeginTransactionSqlException 을 반환하면 mars를 사용할 때 SQL Server 병렬 트랜잭션을 허용하지 않기 때문에 throw됩니다. 이 문제를 방지하려면 읽기 프로그램이 열리기 전에 항상 트랜잭션을 명령, 연결 또는 둘 다와 연결합니다.

추가 정보

적용 대상

BeginTransaction(IsolationLevel, String)

지정된 격리 수준과 트랜잭션 이름으로 데이터베이스 트랜잭션을 시작합니다.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso, System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso, string transactionName);
override this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel, transactionName As String) As SqlTransaction

매개 변수

iso
IsolationLevel

트랜잭션이 실행되어야 하는 격리 수준입니다.

transactionName
String

트랜잭션 이름입니다.

반환

SqlTransaction

새 트랜잭션을 나타내는 개체입니다.

예외

MARS(Multiple Active Result Sets)를 사용하는 경우 병렬 트랜잭션은 허용되지 않습니다.

병렬 트랜잭션은 지원되지 않습니다.

예제

다음 예제에서는 a 및 .를 SqlConnection SqlTransaction만듭니다. 또한 , a 및 Rollback 메서드를 BeginTransactionCommit사용하는 방법을 보여 줍니다.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction(
            IsolationLevel.ReadCommitted, "SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction.
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback("SampleTransaction");
            }
            catch (SqlException ex)
            {
                if (transaction.Connection != null)
                {
                    Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                }
            }

            Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
            Console.WriteLine("Neither record was written to database.");
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction.
        transaction = connection.BeginTransaction( _
          IsolationLevel.ReadCommitted, "SampleTransaction")

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")
        Catch e As Exception
            Try
                transaction.Rollback("SampleTransaction")
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

설명

이 명령은 BEGIN TRANSACTION의 SQL Server 구현에 매핑됩니다.

매개 변수의 값은 메서드의 transactionName 이후 호출 Rollback 및 매개 변수 Save 에서 savePoint 사용할 수 있습니다.

또는 Rollback 메서드를 사용하여 Commit 트랜잭션을 명시적으로 커밋하거나 롤백해야 합니다. SQL Server 트랜잭션 관리 모델이 올바르게 수행되도록 하려면 SQL Server 제공한 것과 같은 다른 트랜잭션 관리 모델을 사용하지 마십시오.

참고

트랜잭션이 커밋되거나 롤백된 후 트랜잭션의 격리 수준은 자동 커밋 모드(SQL Server 기본값)에 있는 모든 후속 명령에 대해 유지됩니다. 이렇게 하면 반복 가능한 읽기의 격리 수준 유지 및 다른 사용자를 행에서 잠그는 등의 예기치 않은 결과가 발생할 수 있습니다. 격리 수준을 기본값(READ COMMITTED)으로 다시 설정하려면 Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED 문을 실행하거나 즉시 SqlTransaction.Commit호출 SqlConnection.BeginTransaction 합니다. SQL Server 격리 수준에 대한 자세한 내용은 트랜잭션 격리 수준을 참조하세요.

SQL Server 트랜잭션에 대한 자세한 내용은 트랜잭션(Transact-SQL)을 참조하세요.

주의

쿼리에서 대량의 데이터와 호출 BeginTransactionSqlException 을 반환하면 mars를 사용할 때 SQL Server 병렬 트랜잭션을 허용하지 않기 때문에 throw됩니다. 이 문제를 방지하려면 읽기 프로그램이 열리기 전에 항상 트랜잭션을 명령, 연결 또는 둘 다와 연결합니다.

추가 정보

적용 대상