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
實作

範例

下列範例會建立SqlConnection SqlTransaction和。The 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

備註

應用程式會藉SqlTransaction由在SqlConnection物件BeginTransaction上呼叫來建立物件。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. 當連接Rollback被終止,或交易已在伺服器上回複時,和都會Commit產生。 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 物件或 null (如果交易不再有效)。Gets the SqlConnection object associated with the transaction, or null if the transaction is no longer valid.

IsolationLevel

指定適用於此交易的 IsolationLevelSpecifies the IsolationLevel for this transaction.

方法

Commit()

認可資料庫交易。Commits the database transaction.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

作為預設雜湊函數。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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.

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()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

適用於

另請參閱