SqlTransaction.Rollback 方法

定義

從暫止狀態回復交易。Rolls back a transaction from a pending state.

多載

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.

Rollback()

從暫止狀態回復交易。Rolls back a transaction from a pending state.

public:
 virtual void Rollback();
public void Rollback ();
abstract member Rollback : unit -> unit
override this.Rollback : unit -> unit
Public Sub Rollback ()

實作

例外狀況

嘗試認可交易時發生錯誤。An error occurred while trying to commit the transaction.

已認可或復原交易。The transaction has already been committed or rolled back.

-或--or-

連線已中斷。The connection is broken.

範例

下列範例會建立 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. 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

備註

Rollback 方法相當於 Transact-sql ROLLBACK TRANSACTION 語句。The Rollback method is equivalent to the Transact-SQL ROLLBACK TRANSACTION statement. 如需詳細資訊,請參閱ROLLBACK TRANSACTION (transact-sql) For more information, see ROLLBACK TRANSACTION (Transact-SQL) .

交易只能從暫止狀態回復(在呼叫 BeginTransaction 之後,但在呼叫 Commit 之前)。The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). 在呼叫 CommitRollback 之前,交易會在處置時復原。The transaction is rolled back in the event it is disposed before Commit or Rollback is called.

注意

在回復交易時,應該一律使用 Try/Catch 例外狀況處理。Try/Catch exception handling should always be used when rolling back a transaction. 如果連接已終止或交易已在伺服器上回複,Rollback 會產生 InvalidOperationExceptionA Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

如需 SQL Server 交易的詳細資訊,請參閱交易(transact-sql)For more information on SQL Server transactions, see Transactions (Transact-SQL).

另請參閱

Rollback(String)

從暫止狀態中復原交易,並指定交易和儲存點名稱。Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

public:
 void Rollback(System::String ^ transactionName);
public void Rollback (string transactionName);
member this.Rollback : string -> unit
Public Sub Rollback (transactionName As String)

參數

transactionName
String

要復原的交易名稱,或要復原的儲存點。The name of the transaction to roll back, or the savepoint to which to roll back.

例外狀況

沒有指定任何交易名稱。No transaction name was specified.

已認可或復原交易。The transaction has already been committed or rolled back.

-或--or-

連線已中斷。The connection is broken.

範例

下列範例會建立 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. 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("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

備註

Rollback 方法相當於 Transact-sql ROLLBACK TRANSACTION 語句。The Rollback method is equivalent to the Transact-SQL ROLLBACK TRANSACTION statement. 如需詳細資訊,請參閱交易(transact-sql)For more information, see Transactions (Transact-SQL).

交易只能從暫止狀態回復(在呼叫 BeginTransaction 之後,但在呼叫 Commit 之前)。The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). 如果在呼叫 CommitRollback 之前處置交易,就會回復。The transaction is rolled back if it is disposed before Commit or Rollback is called.

注意

在回復交易時,應該一律使用 Try/Catch 例外狀況處理。Try/Catch exception handling should always be used when rolling back a transaction. 如果連接已終止或交易已在伺服器上回複,Rollback 會產生 InvalidOperationExceptionA Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

如需 SQL Server 交易的詳細資訊,請參閱交易(transact-sql)For more information on SQL Server transactions, see Transactions (Transact-SQL).

另請參閱

適用於