SqlTransaction SqlTransaction SqlTransaction SqlTransaction Class

Definición

Representa una transacción de Transact-SQL que se realiza en una base de datos de SQL Server.Represents a Transact-SQL transaction to be made in a SQL Server database. Esta clase no puede heredarse.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
Herencia
Implementaciones

Ejemplos

En el ejemplo siguiente se crea un SqlConnection y un SqlTransaction.The following example creates a SqlConnection and a SqlTransaction. También se muestra cómo usar el BeginTransaction, Commit, y Rollback métodos.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. La transacción se revierte cualquier error, o si se elimina sin tener primero que confirma.The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch control de errores se usa para controlar los errores cuando se intenta confirmar o revertir la transacción.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

Comentarios

La aplicación crea un SqlTransaction objeto mediante una llamada a BeginTransaction en el SqlConnection objeto.The application creates a SqlTransaction object by calling BeginTransaction on the SqlConnection object. Todas las operaciones posteriores asociadas con la transacción (por ejemplo, confirmar o anular la transacción), se realizan en el SqlTransaction objeto.All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the SqlTransaction object.

Nota

Try/Catch control de excepciones siempre se debe usar al confirmar o revertir una SqlTransaction.Try/Catch exception handling should always be used when committing or rolling back a SqlTransaction. Ambos Commit y Rollback generar un InvalidOperationException cuando se termina la conexión o si la transacción ya se ha deshecho en el servidor.Both Commit and Rollback generate an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the server.

Para obtener más información sobre las transacciones de SQL Server, vea transacciones explícitas y codificar transacciones eficaces.For more information on SQL Server transactions, see Explicit Transactions and Coding Efficient Transactions.

Propiedades

Connection Connection Connection Connection

Obtiene el objeto SqlConnection asociado a la transacción o null si la transacción ya no es válida.Gets the SqlConnection object associated with the transaction, or null if the transaction is no longer valid.

IsolationLevel IsolationLevel IsolationLevel IsolationLevel

Especifica IsolationLevel para esta transacción.Specifies the IsolationLevel for this transaction.

Métodos

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

Confirma la transacción de base de datos.Commits the database transaction.

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

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.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()

Libera los recursos retenidos por el objeto.Releases the resources that are held by the object.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

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

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Rollback() Rollback() Rollback() Rollback()

Revierte una transacción desde un estado pendiente.Rolls back a transaction from a pending state.

Rollback(String) Rollback(String) Rollback(String) Rollback(String)

Deshace una transacción con un estado pendiente y especifica el nombre de la transacción o del punto de almacenamiento.Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

Save(String) Save(String) Save(String) Save(String)

Crea un punto de almacenamiento en la transacción que se puede utilizar para deshacer parte de la transacción, y especifica el nombre del punto de almacenamiento.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()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Se aplica a

Consulte también: