IDbTransaction Interface

Definição

Representa uma transação a ser realizada em uma fonte de dados e é implementada por provedores de dados .NET Framework que acessam bancos de dados relacionais.Represents a transaction to be performed at a data source, and is implemented by .NET Framework data providers that access relational databases.

public interface class IDbTransaction : IDisposable
public interface IDbTransaction : IDisposable
type IDbTransaction = interface
    interface IDisposable
Public Interface IDbTransaction
Implements IDisposable
Derivado
Implementações

Exemplos

O exemplo a seguir cria instâncias das classes derivadas, SqlConnection e SqlTransaction.The following example creates instances of the derived classes, SqlConnection and SqlTransaction. Ele também demonstra como usar os métodos BeginTransaction, Commite Rollback.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.

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

Comentários

A interface IDbTransaction permite que uma classe de herança implemente uma classe Transaction, que representa a transação a ser executada em uma fonte de dados.The IDbTransaction interface allows an inheriting class to implement a Transaction class, which represents the transaction to be performed at a data source. Para obter mais informações sobre as classes de transação, consulte Transações e simultaneidade.For more information about Transaction classes, see Transactions and Concurrency.

Um aplicativo não cria uma instância da interface de IDbTransaction diretamente, mas cria uma instância de uma classe que herda IDbTransaction.An application does not create an instance of the IDbTransaction interface directly, but creates an instance of a class that inherits IDbTransaction.

As classes que herdam IDbTransaction devem implementar os membros herdados e, normalmente, definir membros adicionais para adicionar funcionalidade específica do provedor.Classes that inherit IDbTransaction must implement the inherited members, and typically define additional members to add provider-specific functionality. Por exemplo, a interface IDbTransaction define o método Commit.For example, the IDbTransaction interface defines the Commit method. Por sua vez, a classe OleDbTransaction herda essa propriedade e também define o método Begin.In turn, the OleDbTransaction class inherits this property, and also defines the Begin method.

Notas aos Implementadores

Para promover a consistência entre .NET Framework provedores de dados, nomeie a classe herdeira no formulário Prv transação em que Prv é o prefixo uniforme fornecido a todas as classes em um namespace específico do provedor de dados .NET Framework.To promote consistency among .NET Framework data providers, name the inheriting class in the form Prv Transaction where Prv is the uniform prefix given to all classes in a specific .NET Framework data provider namespace. Por exemplo, Sql é o prefixo da classe SqlTransaction no namespace System.Data.SqlClient.For example, Sql is the prefix of the SqlTransaction class in the System.Data.SqlClient namespace.

Propriedades

Connection

Especifica o objeto Connection a ser associado com a transação.Specifies the Connection object to associate with the transaction.

IsolationLevel

Especifica o IsolationLevel para essa transação.Specifies the IsolationLevel for this transaction.

Métodos

Commit()

Confirma a transação do banco de dados.Commits the database transaction.

Dispose()

Executa tarefas definidas pelo aplicativo associadas à liberação ou redefinição de recursos não gerenciados.Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

(Herdado de IDisposable)
Rollback()

Reverte uma transação de um estado pendente.Rolls back a transaction from a pending state.

Aplica-se a