Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Método SqlConnection.BeginTransaction (IsolationLevel)

 

Publicado: noviembre de 2016

Inicia una transacción de base de datos con el nivel de aislamiento especificado.

Espacio de nombres:   System.Data.SqlClient
Ensamblado:  System.Data (en System.Data.dll)

public SqlTransaction BeginTransaction(
	IsolationLevel iso
)

Parámetros

iso
Type: System.Data.IsolationLevel

Nivel de aislamiento en el que tiene que ejecutarse la transacción.

Valor devuelto

Type: System.Data.SqlClient.SqlTransaction

Objeto que representa la nueva transacción.

Exception Condition
SqlException

No se permiten transacciones paralelas al usar Conjuntos de resultados activos múltiples (MARS).

InvalidOperationException

No se admiten transacciones paralelas.

This command maps to the ssNoVersion implementation of BEGIN TRANSACTION.

You must explicitly commit or roll back the transaction using the M:System.Data.SqlClient.SqlTransaction.Commit or M:System.Data.SqlClient.SqlTransaction.Rollback method. To make sure that the dnprdnshort Data Provider for ssNoVersion transaction management model performs correctly, avoid using other transaction management models, such as the one provided by ssNoVersion.

System_CAPS_noteNota

After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the ssNoVersion default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the tsql SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call M:System.Data.SqlClient.SqlConnection.BeginTransaction followed immediately by M:System.Data.SqlClient.SqlTransaction.Commit. For more information on ssNoVersion isolation levels, see "Isolation Levels in the Database Engine" in ssNoVersion Books Online.

For more information on ssNoVersion transactions, see "Explicit Transactions" and "Coding Efficient Transactions" in ssNoVersion Books Online.

System_CAPS_cautionPrecaución

When your query returns a large amount of data and calls BeginTransaction, a T:System.Data.SqlClient.SqlException is thrown because ssNoVersion does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.

The following example creates a T:System.Data.SqlClient.SqlConnection and a T:System.Data.SqlClient.SqlTransaction. It also demonstrates how to use the M:System.Data.SqlClient.SqlConnection.BeginTransaction, a M:System.Data.SqlClient.SqlTransaction.Commit, and M:System.Data.SqlClient.SqlTransaction.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(IsolationLevel.ReadCommitted);

        // 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();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback();
            }
            catch (SqlException ex)
            {
                if (transaction.Connection != null)
                {
                    Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                }
            }

            Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
            Console.WriteLine("Neither record was written to database.");
        }
    }
}

.NET Framework
Disponible desde 1.1
Volver al principio
Mostrar: