Editar

Partilhar via


SqlTransaction Class

Definition

Caution

Use the Microsoft.Data.SqlClient package instead.

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
public ref class SqlTransaction sealed : MarshalByRefObject, IDisposable, System::Data::IDbTransaction
public sealed class SqlTransaction : System.Data.Common.DbTransaction
[System.Obsolete("Use the Microsoft.Data.SqlClient package instead.")]
public sealed class SqlTransaction : System.Data.Common.DbTransaction
public sealed class SqlTransaction : MarshalByRefObject, IDisposable, System.Data.IDbTransaction
type SqlTransaction = class
    inherit DbTransaction
[<System.Obsolete("Use the Microsoft.Data.SqlClient package instead.")>]
type SqlTransaction = class
    inherit DbTransaction
type SqlTransaction = class
    inherit MarshalByRefObject
    interface IDbTransaction
    interface IDisposable
Public NotInheritable Class SqlTransaction
Inherits DbTransaction
Public NotInheritable Class SqlTransaction
Inherits MarshalByRefObject
Implements IDbTransaction, IDisposable
Inheritance
SqlTransaction
Inheritance
Inheritance
SqlTransaction
Attributes
Implements

Examples

The following example creates a SqlConnection and a SqlTransaction. 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 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();

        // 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

Remarks

The application creates a SqlTransaction object by calling BeginTransaction on the SqlConnection object. All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the SqlTransaction object.

Note

Try/Catch exception handling should always be used when committing or rolling back a SqlTransaction. Both Commit and Rollback generate an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

For more information on SQL Server transactions, see Explicit Transactions and Coding Efficient Transactions.

Properties

Connection

Gets the SqlConnection object associated with the transaction, or null if the transaction is no longer valid.

DbConnection

When overridden in a derived class, gets the DbConnection object associated with the transaction.

(Inherited from DbTransaction)
IsolationLevel

Specifies the IsolationLevel for this transaction.

SupportsSavepoints

Gets a value that indicates whether this DbTransaction instance supports database savepoints. If false, the methods SaveAsync(String, CancellationToken), RollbackAsync(String, CancellationToken) and ReleaseAsync(String, CancellationToken) as well as their synchronous counterparts are expected to throw NotSupportedException.

(Inherited from DbTransaction)

Methods

Commit()

Commits the database transaction.

CommitAsync(CancellationToken)

Asynchronously commits the database transaction.

(Inherited from DbTransaction)
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()

Releases the resources that are held by the object.

Dispose()

Releases the unmanaged resources used by the DbTransaction.

(Inherited from DbTransaction)
Dispose(Boolean)

Releases the unmanaged resources used by the DbTransaction and optionally releases the managed resources.

(Inherited from DbTransaction)
DisposeAsync()

Asynchronously disposes the transaction object.

(Inherited from DbTransaction)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Release(String)

Destroys a savepoint previously defined in the current transaction. This allows the system to reclaim some resources before the transaction ends.

(Inherited from DbTransaction)
ReleaseAsync(String, CancellationToken)

Destroys a savepoint previously defined in the current transaction. This allows the system to reclaim some resources before the transaction ends.

(Inherited from DbTransaction)
Rollback()

Rolls back a transaction from a pending state.

Rollback(String)

Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

RollbackAsync(CancellationToken)

Asynchronously rolls back a transaction from a pending state.

(Inherited from DbTransaction)
RollbackAsync(String, CancellationToken)

Rolls back all commands that were executed after the specified savepoint was established.

(Inherited from DbTransaction)
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.

SaveAsync(String, CancellationToken)

Creates a savepoint in the transaction. This allows all commands that are executed after the savepoint was established to be rolled back, restoring the transaction state to what it was at the time of the savepoint.

(Inherited from DbTransaction)
ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

IDbTransaction.Connection

Gets the DbConnection object associated with the transaction, or a null reference if the transaction is no longer valid.

(Inherited from DbTransaction)

Applies to

See also