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

範例

下列範例會建立SqlConnectionSqlTransactionThe following example creates a SqlConnection and a SqlTransaction. 它也會示範如何使用BeginTransactionCommit,和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 認可或回復時,應該一律使用例外狀況處理SqlTransactionTry/Catch exception handling should always be used when committing or rolling back a SqlTransaction. 兩者CommitRollback產生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

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

方法

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

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

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

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

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

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

取得目前執行個體的 TypeGets 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 的淺層複本 (Shallow Copy)。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)

適用於

另請參閱