SqlTransaction SqlTransaction SqlTransaction SqlTransaction Class

정의

SQL Server 데이터베이스에 만들 Transact-SQL 트랜잭션을 나타냅니다.Represents a Transact-SQL transaction to be made in a SQL Server database. 이 클래스는 상속될 수 없습니다.This class cannot be inherited.

public ref class SqlTransaction sealed : System::Data::Common::DbTransaction, IDisposable
public sealed class SqlTransaction : System.Data.Common.DbTransaction, IDisposable
type SqlTransaction = class
    inherit DbTransaction
    interface IDbTransaction
    interface IDisposable
Public NotInheritable Class SqlTransaction
Inherits DbTransaction
Implements IDisposable
상속
구현

예제

다음 예제는 SqlConnectionSqlTransaction합니다.The following example creates a SqlConnection and a SqlTransaction. 사용 하는 방법을 보여 줍니다 합니다 BeginTransaction, Commit, 및 Rollback 메서드.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. 트랜잭션이 롤백되면 모든 오류에 대해 첫 번째 하지 않고 삭제 될 경우 또는 커밋입니다.The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch 커밋 또는 트랜잭션을 롤백하는 동안 오류를 처리 하는 오류 처리 사용 됩니다.Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

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();
            }
            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("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

설명

애플리케이션을 SqlTransaction 호출 하 여 개체 BeginTransactionSqlConnection 개체입니다.The application creates a SqlTransaction object by calling BeginTransaction on the SqlConnection object. 예를 들어, 커밋, 트랜잭션을 중단 트랜잭션과 관련 된 모든 후속 작업에서 수행 되는 SqlTransaction 개체입니다.All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the SqlTransaction object.

참고

Try/Catch 커밋 또는 롤백하는 경우에 항상 예외 처리를 사용 해야는 SqlTransaction합니다.Try/Catch exception handling should always be used when committing or rolling back a SqlTransaction. 둘 다 Commit 하 고 Rollback 생성을 InvalidOperationException 연결이 종료 되는 경우 또는 서버에서 트랜잭션이 이미 롤백된 경우.Both Commit and Rollback generate an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

SQL Server 트랜잭션에 대 한 자세한 내용은 참조 하세요. 명시적 트랜잭션을 하 고 효율적인 트랜잭션 코딩합니다.For more information on SQL Server transactions, see Explicit Transactions and Coding Efficient Transactions.

속성

Connection Connection Connection Connection

트랜잭션과 관련된 SqlConnection 개체를 가져오거나 트랜잭션이 더 이상 유효하지 않으면 null입니다.Gets the SqlConnection object associated with the transaction, or null if the transaction is no longer valid.

IsolationLevel IsolationLevel IsolationLevel IsolationLevel

이 트랜잭션에 대한 IsolationLevel을 지정합니다.Specifies the IsolationLevel for this transaction.

메서드

Commit() Commit() Commit() Commit()

데이터베이스 트랜잭션을 커밋합니다.Commits the database transaction.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

개체에서 보유한 리소스를 해제합니다.Releases the resources that are held by the object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Rollback() Rollback() Rollback() Rollback()

보류 상태에서 트랜잭션을 롤백합니다.Rolls back a transaction from a pending state.

Rollback(String) Rollback(String) Rollback(String) Rollback(String)

트랜잭션을 보류 상태에서 롤백하고, 트랜잭션이나 저장점 이름을 지정합니다.Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

Save(String) Save(String) Save(String) Save(String)

트랜잭션의 일부를 롤백하는 데 사용할 수 있는 트랜잭션에 저장점을 만들고, 저장점 이름을 지정합니다.Creates a savepoint in the transaction that can be used to roll back a part of the transaction, and specifies the savepoint name.

ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

적용 대상

추가 정보