OdbcConnection.BeginTransaction Метод

Определение

Начинает транзакцию в источнике данных.Starts a transaction at the data source.

Перегрузки

BeginTransaction()

Начинает транзакцию в источнике данных.Starts a transaction at the data source.

BeginTransaction(IsolationLevel)

Начинает транзакцию в источнике данных, используя заданное значение IsolationLevel.Starts a transaction at the data source with the specified IsolationLevel value.

BeginTransaction()

Начинает транзакцию в источнике данных.Starts a transaction at the data source.

public:
 System::Data::Odbc::OdbcTransaction ^ BeginTransaction();
public System.Data.Odbc.OdbcTransaction BeginTransaction ();
override this.BeginTransaction : unit -> System.Data.Odbc.OdbcTransaction
member this.BeginTransaction : unit -> System.Data.Odbc.OdbcTransaction
Public Function BeginTransaction () As OdbcTransaction

Возвращаемое значение

OdbcTransaction

Объект, представляющий новую транзакцию.An object representing the new transaction.

Исключения

Транзакция активна в текущий момент.A transaction is currently active. Параллельные транзакции не поддерживаются.Parallel transactions are not supported.

Примеры

В следующем примере создаются OdbcConnection и OdbcTransaction .The following example creates an OdbcConnection and an OdbcTransaction. В нем также показано, как использовать BeginTransaction Commit методы, и Rollback .It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.

public static void ExecuteTransaction(string connectionString)
{
    using (OdbcConnection connection =
               new OdbcConnection(connectionString))
    {
        OdbcCommand command = new OdbcCommand();
        OdbcTransaction transaction = null;

        // Set the Connection to the new OdbcConnection.
        command.Connection = connection;

        // Open the connection and execute the transaction.
        try
        {
            connection.Open();

            // Start a local transaction
            transaction = connection.BeginTransaction();

            // Assign transaction object for a pending local transaction.
            command.Connection = connection;
            command.Transaction = transaction;

            // Execute the commands.
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            try
            {
                // Attempt to roll back the transaction.
                transaction.Rollback();
            }
            catch
            {
                // Do nothing here; transaction is not active.
            }
        }
        // The connection is automatically closed when the
        // code exits the using block.
    }
Public Sub ExecuteTransaction(ByVal connectionString As String)

    Using connection As New OdbcConnection(connectionString)
        Dim command As New OdbcCommand()
        Dim transaction As OdbcTransaction

        ' Set the Connection to the new OdbcConnection.
        command.Connection = connection

        ' Open the connection and execute the transaction.
        Try
            connection.Open()

            ' Start a local transaction.
            transaction = connection.BeginTransaction()

            ' Assign transaction object for a pending local transaction.
            command.Connection = connection
            command.Transaction = transaction

            ' Execute the commands.
            command.CommandText = _
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()

            ' Commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine(ex.Message)
            ' Try to rollback the transaction
            Try
                transaction.Rollback()

            Catch
                ' Do nothing here; transaction is not active.
            End Try
        End Try
        ' The connection is automatically closed when the
        ' code exits the Using block.
    End Using
End Sub

Комментарии

Для фиксации или отката транзакции необходимо явно использовать Commit Rollback методы или.To commit or roll back the transaction, you must explicitly use the Commit or Rollback methods.

Чтобы убедиться, что поставщик данных платформа .NET Framework для модели управления транзакциями ODBC работает правильно, не используйте другие модели управления транзакциями, например, предоставляемые источником данных.To make sure that the .NET Framework Data Provider for ODBC transaction management model performs correctly, avoid using other transaction management models, such as those provided by the data source.

Примечание

Если уровень изоляции не указан, то уровень изоляции будет определяться используемым драйвером.If you do not specify an isolation level, the isolation level will be determined by the driver being used. Чтобы указать уровень изоляции с помощью BeginTransaction метода, используйте перегрузку, которая принимает isolevel параметр.To specify an isolation level with the BeginTransaction method, use the overload that takes the isolevel parameter.

Применяется к

BeginTransaction(IsolationLevel)

Начинает транзакцию в источнике данных, используя заданное значение IsolationLevel.Starts a transaction at the data source with the specified IsolationLevel value.

public:
 System::Data::Odbc::OdbcTransaction ^ BeginTransaction(System::Data::IsolationLevel isolevel);
public System.Data.Odbc.OdbcTransaction BeginTransaction (System.Data.IsolationLevel isolevel);
override this.BeginTransaction : System.Data.IsolationLevel -> System.Data.Odbc.OdbcTransaction
member this.BeginTransaction : System.Data.IsolationLevel -> System.Data.Odbc.OdbcTransaction
Public Function BeginTransaction (isolevel As IsolationLevel) As OdbcTransaction

Параметры

isolevel
IsolationLevel

Уровень изоляции транзакции для этого подключения.The transaction isolation level for this connection. Если уровень изоляции не указан, используется уровень изоляции, установленный для драйвера по умолчанию.If you do not specify an isolation level, the default isolation level for the driver is used.

Возвращаемое значение

OdbcTransaction

Объект, представляющий новую транзакцию.An object representing the new transaction.

Исключения

Транзакция активна в текущий момент.A transaction is currently active. Параллельные транзакции не поддерживаются.Parallel transactions are not supported.

Примеры

В следующем примере создаются OdbcConnection и OdbcTransaction .The following example creates an OdbcConnection and an OdbcTransaction. В нем также показано, как использовать BeginTransaction Commit методы, и Rollback .It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods.

public static void ExecuteTransaction(string connectionString)
{
    using (OdbcConnection connection =
               new OdbcConnection(connectionString))
    {
        OdbcCommand command = new OdbcCommand();
        OdbcTransaction transaction = null;

        // Set the Connection to the new OdbcConnection.
        command.Connection = connection;

        // Open the connection and execute the transaction.
        try
        {
            connection.Open();

            // Start a local transaction
            transaction = connection.BeginTransaction();

            // Assign transaction object for a pending local transaction.
            command.Connection = connection;
            command.Transaction = transaction;

            // Execute the commands.
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            try
            {
                // Attempt to roll back the transaction.
                transaction.Rollback();
            }
            catch
            {
                // Do nothing here; transaction is not active.
            }
        }
        // The connection is automatically closed when the
        // code exits the using block.
    }
Public Sub ExecuteTransaction(ByVal connectionString As String)

    Using connection As New OdbcConnection(connectionString)
        Dim command As New OdbcCommand()
        Dim transaction As OdbcTransaction

        ' Set the Connection to the new OdbcConnection.
        command.Connection = connection

        ' Open the connection and execute the transaction.
        Try
            connection.Open()

            ' Start a local transaction.
            transaction = connection.BeginTransaction()

            ' Assign transaction object for a pending local transaction.
            command.Connection = connection
            command.Transaction = transaction

            ' Execute the commands.
            command.CommandText = _
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()

            ' Commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine(ex.Message)
            ' Try to rollback the transaction
            Try
                transaction.Rollback()

            Catch
                ' Do nothing here; transaction is not active.
            End Try
        End Try
        ' The connection is automatically closed when the
        ' code exits the Using block.
    End Using
End Sub

Комментарии

Для фиксации или отката транзакции необходимо явно использовать Commit Rollback методы или.To commit or roll back the transaction, you must explicitly use the Commit or Rollback methods.

Чтобы убедиться, что поставщик данных платформа .NET Framework для модели управления транзакциями ODBC работает правильно, не используйте другие модели управления транзакциями, например, предоставляемые источником данных.To make sure that the .NET Framework Data Provider for ODBC transaction management model performs correctly, avoid using other transaction management models, such as those provided by the data source.

Применяется к