SqlConnection.BeginTransaction Methode

Definitie

Hiermee start u een databasetransactie.

Overloads

Name Description
BeginTransaction()

Hiermee start u een databasetransactie.

BeginTransaction(IsolationLevel)

Hiermee start u een databasetransactie met het opgegeven isolatieniveau.

BeginTransaction(String)

Hiermee start u een databasetransactie met de opgegeven transactienaam.

BeginTransaction(IsolationLevel, String)

Hiermee start u een databasetransactie met het opgegeven isolatieniveau en de transactienaam.

BeginTransaction()

Hiermee start u een databasetransactie.

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

Retouren

Een object dat de nieuwe transactie vertegenwoordigt.

Uitzonderingen

Parallelle transacties zijn niet toegestaan wanneer u MARS (Multiple Active Result Sets) gebruikt.

Parallelle transacties worden niet ondersteund.

Voorbeelden

In het volgende voorbeeld wordt een SqlConnection en een SqlTransaction. Het laat ook zien hoe u de BeginTransaction, a Commiten Rollback methoden gebruikt.

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();

        // 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()

        ' 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

Opmerkingen

Met deze opdracht wordt de SQL Server implementatie van BEGIN TRANSACTION toegewezen.

U moet de transactie expliciet doorvoeren of terugdraaien met behulp van de Commit of Rollback methode. Om ervoor te zorgen dat het .NET Framework Data Provider voor SQL Server transactiebeheermodel correct wordt uitgevoerd, vermijdt u het gebruik van andere modellen voor transactiebeheer, zoals die van SQL Server.

Note

Als u geen isolatieniveau opgeeft, wordt het standaardisolatieniveau gebruikt. Als u een isolatieniveau met de BeginTransaction methode wilt opgeven, gebruikt u de overbelasting die de iso parameter (BeginTransaction) gebruikt. Het isolatieniveau dat is ingesteld voor een transactie blijft bestaan nadat de transactie is voltooid en totdat de verbinding is gesloten of verwijderd. Als u het isolatieniveau instelt op Momentopname in een database waarvoor het isolatieniveau voor momentopnamen niet is ingeschakeld, wordt er geen uitzondering gegenereerd. De transactie wordt voltooid met behulp van het standaardisolatieniveau.

Waarschuwing

Als een transactie wordt gestart en een fout op niveau 16 of hoger optreedt op de server, wordt de transactie pas teruggedraaid als de Read methode wordt aangeroepen. Er wordt geen uitzondering gegenereerd op ExecuteReader.

Waarschuwing

Wanneer uw query een grote hoeveelheid gegevens retourneert en BeginTransaction aanroept, wordt er een SqlException gegenereerd omdat SQL Server parallelle transacties niet toestaat bij het gebruik van MARS. Om dit probleem te voorkomen, koppelt u altijd een transactie aan de opdracht, de verbinding of beide voordat lezers worden geopend.

Zie Transactions (Transact-SQL) voor meer informatie over SQL Server transacties.

Zie ook

Van toepassing op

BeginTransaction(IsolationLevel)

Hiermee start u een databasetransactie met het opgegeven isolatieniveau.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso);
public System.Data.SqlClient.SqlTransaction BeginTransaction(System.Data.IsolationLevel iso);
member this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
override this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel) As SqlTransaction

Parameters

iso
IsolationLevel

Het isolatieniveau waaronder de transactie moet worden uitgevoerd.

Retouren

Een object dat de nieuwe transactie vertegenwoordigt.

Uitzonderingen

Parallelle transacties zijn niet toegestaan wanneer u MARS (Multiple Active Result Sets) gebruikt.

Parallelle transacties worden niet ondersteund.

Voorbeelden

In het volgende voorbeeld wordt een SqlConnection en een SqlTransaction. Het laat ook zien hoe u de BeginTransaction, a Commiten Rollback methoden gebruikt.

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.");
        }
    }
}
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(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 e As Exception
            Try
                transaction.Rollback()
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

Opmerkingen

Met deze opdracht wordt de SQL Server implementatie van BEGIN TRANSACTION toegewezen.

U moet de transactie expliciet doorvoeren of terugdraaien met behulp van de Commit of Rollback methode. Om ervoor te zorgen dat het .NET Framework Data Provider voor SQL Server transactiebeheermodel correct wordt uitgevoerd, vermijdt u het gebruik van andere modellen voor transactiebeheer, zoals die van SQL Server.

Note

Nadat een transactie is doorgevoerd of teruggedraaid, blijft het isolatieniveau van de transactie behouden voor alle volgende opdrachten die zich in de modus autocommit bevinden (de standaardinstelling van de SQL Server). Dit kan onverwachte resultaten opleveren, zoals een isolatieniveau van HERHAALBARE LEESbewerkingen die behouden blijven en andere gebruikers buiten een rij vergrendelen. Als u het isolatieniveau opnieuw wilt instellen op de standaardinstelling (READ COMMIT), voert u de instructie Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMIT uit of roept u SqlConnection.BeginTransaction aan, gevolgd door SqlTransaction.Commit. Zie Transaction-isolatieniveaus voor meer informatie over SQL Server isolatieniveaus.

Zie Transactions (Transact-SQL) voor meer informatie over SQL Server transacties.

Waarschuwing

Wanneer uw query een grote hoeveelheid gegevens retourneert en BeginTransaction aanroept, wordt er een SqlException gegenereerd omdat SQL Server parallelle transacties niet toestaat bij het gebruik van MARS. Om dit probleem te voorkomen, koppelt u altijd een transactie aan de opdracht, de verbinding of beide voordat lezers worden geopend.

Zie ook

Van toepassing op

BeginTransaction(String)

Hiermee start u een databasetransactie met de opgegeven transactienaam.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction(string transactionName);
member this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
override this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (transactionName As String) As SqlTransaction

Parameters

transactionName
String

De naam van de transactie.

Retouren

Een object dat de nieuwe transactie vertegenwoordigt.

Uitzonderingen

Parallelle transacties zijn niet toegestaan wanneer u MARS (Multiple Active Result Sets) gebruikt.

Parallelle transacties worden niet ondersteund.

Voorbeelden

In het volgende voorbeeld wordt een SqlConnection en een SqlTransaction. Het laat ook zien hoe u de BeginTransaction, a Commiten Rollback methoden gebruikt.

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("SampleTransaction");
            }
            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("Exception Type: {0}", ex.GetType())
            Console.WriteLine("  Message: {0}", ex.Message)

            ' Attempt to roll back the transaction.
            Try
                transaction.Rollback("SampleTransaction")

            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

Opmerkingen

Met deze opdracht wordt de SQL Server implementatie van BEGIN TRANSACTION toegewezen.

De lengte van de transactionName parameter mag niet langer zijn dan 32 tekens. Anders wordt er een uitzondering gegenereerd.

De waarde in de transactionName parameter kan worden gebruikt in latere aanroepen naar Rollback en in de savePoint parameter van de Save methode.

U moet de transactie expliciet doorvoeren of terugdraaien met behulp van de Commit of Rollback methode. Om ervoor te zorgen dat het .NET Framework Data Provider voor SQL Server transactiebeheermodel correct wordt uitgevoerd, vermijdt u het gebruik van andere modellen voor transactiebeheer, zoals die van SQL Server.

Zie Transactions (Transact-SQL) voor meer informatie over SQL Server transacties.

Waarschuwing

Wanneer uw query een grote hoeveelheid gegevens retourneert en BeginTransaction aanroept, wordt er een SqlException gegenereerd omdat SQL Server parallelle transacties niet toestaat bij het gebruik van MARS. Om dit probleem te voorkomen, koppelt u altijd een transactie aan de opdracht, de verbinding of beide voordat lezers worden geopend.

Zie ook

Van toepassing op

BeginTransaction(IsolationLevel, String)

Hiermee start u een databasetransactie met het opgegeven isolatieniveau en de transactienaam.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso, System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction(System.Data.IsolationLevel iso, string transactionName);
member this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
override this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel, transactionName As String) As SqlTransaction

Parameters

iso
IsolationLevel

Het isolatieniveau waaronder de transactie moet worden uitgevoerd.

transactionName
String

De naam van de transactie.

Retouren

Een object dat de nieuwe transactie vertegenwoordigt.

Uitzonderingen

Parallelle transacties zijn niet toegestaan wanneer u MARS (Multiple Active Result Sets) gebruikt.

Parallelle transacties worden niet ondersteund.

Voorbeelden

In het volgende voorbeeld wordt een SqlConnection en een SqlTransaction. Het laat ook zien hoe u de BeginTransaction, a Commiten Rollback methoden gebruikt.

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, "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();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback("SampleTransaction");
            }
            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.");
        }
    }
}
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( _
          IsolationLevel.ReadCommitted, "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()
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")
        Catch e As Exception
            Try
                transaction.Rollback("SampleTransaction")
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

Opmerkingen

Met deze opdracht wordt de SQL Server implementatie van BEGIN TRANSACTION toegewezen.

De waarde in de transactionName parameter kan worden gebruikt in latere aanroepen naar Rollback en in de savePoint parameter van de Save methode.

U moet de transactie expliciet doorvoeren of terugdraaien met behulp van de Commit of Rollback methode. Om ervoor te zorgen dat het SQL Server transactiebeheermodel correct wordt uitgevoerd, vermijdt u het gebruik van andere modellen voor transactiebeheer, zoals het model dat wordt geleverd door SQL Server.

Note

Nadat een transactie is doorgevoerd of teruggedraaid, blijft het isolatieniveau van de transactie behouden voor alle volgende opdrachten die zich in de modus autocommit bevinden (de standaardinstelling van de SQL Server). Dit kan onverwachte resultaten opleveren, zoals een isolatieniveau van HERHAALBARE LEESbewerkingen die behouden blijven en andere gebruikers buiten een rij vergrendelen. Als u het isolatieniveau opnieuw wilt instellen op de standaardinstelling (READ COMMIT), voert u de instructie Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMIT uit of roept u SqlConnection.BeginTransaction aan, gevolgd door SqlTransaction.Commit. Zie Transaction-isolatieniveaus voor meer informatie over SQL Server isolatieniveaus.

Zie Transactions (Transact-SQL) voor meer informatie over SQL Server transacties.

Waarschuwing

Wanneer uw query een grote hoeveelheid gegevens retourneert en BeginTransaction aanroept, wordt er een SqlException gegenereerd omdat SQL Server parallelle transacties niet toestaat bij het gebruik van MARS. Om dit probleem te voorkomen, koppelt u altijd een transactie aan de opdracht, de verbinding of beide voordat lezers worden geopend.

Zie ook

Van toepassing op