SqlTransaction Clase

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 se puede heredar.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
SqlTransaction
Herencia
Herencia
SqlTransaction
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 los métodos BeginTransaction, Commity Rollback.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. La transacción se revierte en caso de error, o si se desecha sin que se confirme primero.The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch el control de errores se utiliza para controlar los errores que se producen al intentar 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 objeto SqlTransaction llamando a BeginTransaction en el objeto SqlConnection.The application creates a SqlTransaction object by calling BeginTransaction on the SqlConnection object. Todas las operaciones posteriores asociadas a la transacción (por ejemplo, la confirmación o la anulación de la transacción) se realizan en el objeto de SqlTransaction.All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the SqlTransaction object.

Nota

Try/se debe usar el control de excepciones de Catch siempre que se confirme o revierta una SqlTransaction.Try/Catch exception handling should always be used when committing or rolling back a SqlTransaction. Tanto Commit como Rollback generan un InvalidOperationException si se termina la conexión o si la transacción ya se ha revertido 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 codificación de transacciones eficientes.For more information on SQL Server transactions, see Explicit Transactions and Coding Efficient Transactions.

Propiedades

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.

DbConnection

Cuando se invalida en una clase derivada, obtiene el objeto DbConnection asociado a la transacción.When overridden in a derived class, gets the DbConnection object associated with the transaction.

(Heredado de DbTransaction)
IsolationLevel

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

Métodos

Commit()

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

CommitAsync(CancellationToken)

Confirma de forma asincrónica la transacción de base de datos.Asynchronously commits the database transaction.

(Heredado de DbTransaction)
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.

(Heredado de MarshalByRefObject)
Dispose()

Libera los recursos que mantiene el objeto.Releases the resources that are held by the object.

Dispose(Boolean)

Libera los recursos no administrados que usa el objeto DbTransaction y, opcionalmente, libera los recursos administrados.Releases the unmanaged resources used by the DbTransaction and optionally releases the managed resources.

(Heredado de DbTransaction)
DisposeAsync()

Desecha de forma asincrónica el objeto de transacción.Asynchronously diposes the transaction object.

(Heredado de DbTransaction)
Equals(Object)

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

(Heredado de Object)
GetHashCode()

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

(Heredado de Object)
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.

(Heredado de MarshalByRefObject)
GetType()

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

(Heredado de Object)
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.

(Heredado de MarshalByRefObject)
MemberwiseClone()

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

(Heredado de Object)
MemberwiseClone(Boolean)

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

(Heredado de MarshalByRefObject)
Rollback()

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

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.

RollbackAsync(CancellationToken)

Revierte de forma asincrónica una transacción desde un estado pendiente.Asynchronously rolls back a transaction from a pending state.

(Heredado de DbTransaction)
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()

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

(Heredado de Object)

Implementaciones de interfaz explícitas

IDbTransaction.Connection

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

(Heredado de DbTransaction)

Se aplica a

Consulte también: