SqlTransaction 类

定义

表示将在 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
继承
SqlTransaction
实现

示例

下面的示例创建 SqlConnectionSqlTransactionThe following example creates a SqlConnection and a SqlTransaction. 它还演示了如何使用 BeginTransactionCommitRollback 方法。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

注解

应用程序通过在 SqlConnection 对象上调用 BeginTransaction 来创建 SqlTransaction 对象。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. 如果连接终止,或者事务已在服务器上回滚,则 CommitRollback 都会生成 InvalidOperationExceptionBoth 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

获取与该事务关联的 SqlConnection 对象,或者如果该事务不再有效,则为 nullGets the SqlConnection object associated with the transaction, or null if the transaction is no longer valid.

DbConnection

在派生类中重写时,获取与事务关联的 DbConnection 对象。When overridden in a derived class, gets the DbConnection object associated with the transaction.

(继承自 DbTransaction)
IsolationLevel

为该事务指定 IsolationLevelSpecifies the IsolationLevel for this transaction.

方法

Commit()

提交数据库事务。Commits the database transaction.

CommitAsync(CancellationToken)

异步提交数据库事务。Asynchronously commits the database transaction.

(继承自 DbTransaction)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

释放由该对象占用的资源。Releases the resources that are held by the object.

Dispose(Boolean)

释放 DbTransaction 使用的非托管资源,并选择性地释放托管资源。Releases the unmanaged resources used by the DbTransaction and optionally releases the managed resources.

(继承自 DbTransaction)
DisposeAsync()

异步处置事务对象。Asynchronously diposes the transaction object.

(继承自 DbTransaction)
Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
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.

(继承自 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.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

显式接口实现

IDbTransaction.Connection

获取与事务关联的 DbConnection 对象,或空引用(如果该事务不再有效)。Gets the DbConnection object associated with the transaction, or a null reference if the transaction is no longer valid.

(继承自 DbTransaction)

适用于

另请参阅