SqlConnection.BeginTransaction Metoda

Definice

Spustí databázovou transakci.

Přetížení

Name Description
BeginTransaction()

Spustí databázovou transakci.

BeginTransaction(IsolationLevel)

Spustí databázovou transakci se zadanou úrovní izolace.

BeginTransaction(String)

Spustí databázovou transakci se zadaným názvem transakce.

BeginTransaction(IsolationLevel, String)

Spustí databázovou transakci se zadanou úrovní izolace a názvem transakce.

BeginTransaction()

Zdroj:
System.Data.SqlClient.notsupported.cs

Spustí databázovou transakci.

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

Návraty

Objekt představující novou transakci.

Výjimky

Paralelní transakce nejsou povoleny při použití více aktivních sad výsledků (MARS).

Paralelní transakce nejsou podporovány.

Příklady

Následující příklad vytvoří SqlConnection a .SqlTransaction Ukazuje také, jak používat BeginTransaction, a Commita Rollback metody.

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

Poznámky

Tento příkaz se mapuje na SQL Server implementaci BEGIN TRANSACTION.

Transakce musíte explicitně potvrdit nebo vrátit zpět pomocí Commit metody nebo Rollback metody. Abyste měli jistotu, že Zprostředkovatel dat .NET Framework pro model správy transakcí SQL Server funguje správně, nepoužívejte jiné modely správy transakcí, jako je například model poskytovaný SQL Server.

Note

Pokud nezadáte úroveň izolace, použije se výchozí úroveň izolace. Pokud chcete určit úroveň izolace pomocí BeginTransaction metody, použijte přetížení, které přebírá iso parametr (BeginTransaction). Úroveň izolace nastavená pro transakci přetrvává po dokončení transakce a dokud není připojení uzavřeno nebo uvolněno. Nastavení úrovně izolace na Snímek v databázi, kde není povolená úroveň izolace snímku, nevyvolá výjimku. Transakce se dokončí pomocí výchozí úrovně izolace.

Caution

Pokud se na serveru spustí transakce a na serveru dojde k chybě úrovně 16 nebo vyšší, transakce nebude vrácena zpět, dokud Read se metoda nevyvolá. U ExecuteReader se nevyvolá žádná výjimka.

Caution

Když dotaz vrátí velké množství dat a volá BeginTransaction, vyvolá se SqlException, protože SQL Server neumožňuje paralelní transakce při použití MARS. Chcete-li se tomuto problému vyhnout, vždy přidružte transakci k příkazu, připojení nebo obojí před otevřením všech čtenářů.

Další informace o transakcích SQL Server najdete v tématu Transactions (Transact-SQL).

Viz také

Platí pro

BeginTransaction(IsolationLevel)

Zdroj:
System.Data.SqlClient.notsupported.cs

Spustí databázovou transakci se zadanou úrovní izolace.

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

Parametry

iso
IsolationLevel

Úroveň izolace, pod kterou má transakce běžet.

Návraty

Objekt představující novou transakci.

Výjimky

Paralelní transakce nejsou povoleny při použití více aktivních sad výsledků (MARS).

Paralelní transakce nejsou podporovány.

Příklady

Následující příklad vytvoří SqlConnection a .SqlTransaction Ukazuje také, jak používat BeginTransaction, a Commita Rollback metody.

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

Poznámky

Tento příkaz se mapuje na SQL Server implementaci BEGIN TRANSACTION.

Transakce musíte explicitně potvrdit nebo vrátit zpět pomocí Commit metody nebo Rollback metody. Abyste měli jistotu, že Zprostředkovatel dat .NET Framework pro model správy transakcí SQL Server funguje správně, nepoužívejte jiné modely správy transakcí, jako je například model poskytovaný SQL Server.

Note

Jakmile je transakce potvrzena nebo vrácena zpět, úroveň izolace transakce přetrvává pro všechny následné příkazy, které jsou v režimu automatickéhocommit (SQL Server výchozí). To může vést k neočekávaným výsledkům, jako je například úroveň izolace funkce REPEATABLE READ, která se zachová a uzamkne ostatní uživatele mimo řádek. Pokud chcete obnovit výchozí úroveň izolace (READ COMMITTED), spusťte příkaz Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED nebo zavolejte SqlConnection.BeginTransaction následované okamžitě SqlTransaction.Commit. Další informace o úrovních izolace SQL Server najdete v tématu .

Další informace o transakcích SQL Server najdete v tématu Transactions (Transact-SQL).

Caution

Když dotaz vrátí velké množství dat a volá BeginTransaction, vyvolá se SqlException, protože SQL Server neumožňuje paralelní transakce při použití MARS. Chcete-li se tomuto problému vyhnout, vždy přidružte transakci k příkazu, připojení nebo obojí před otevřením všech čtenářů.

Viz také

Platí pro

BeginTransaction(String)

Zdroj:
System.Data.SqlClient.notsupported.cs

Spustí databázovou transakci se zadaným názvem transakce.

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

Parametry

transactionName
String

Název transakce.

Návraty

Objekt představující novou transakci.

Výjimky

Paralelní transakce nejsou povoleny při použití více aktivních sad výsledků (MARS).

Paralelní transakce nejsou podporovány.

Příklady

Následující příklad vytvoří SqlConnection a .SqlTransaction Ukazuje také, jak používat BeginTransaction, a Commita Rollback metody.

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

Poznámky

Tento příkaz se mapuje na SQL Server implementaci BEGIN TRANSACTION.

Délka parametru transactionName nesmí překročit 32 znaků, jinak se vyvolá výjimka.

Hodnotu v parametru transactionName lze použít v pozdějších voláních Rollback a v savePoint parametru Save metody.

Transakce musíte explicitně potvrdit nebo vrátit zpět pomocí Commit metody nebo Rollback metody. Abyste měli jistotu, že Zprostředkovatel dat .NET Framework pro model správy transakcí SQL Server funguje správně, nepoužívejte jiné modely správy transakcí, jako je například model poskytovaný SQL Server.

Další informace o transakcích SQL Server najdete v tématu Transactions (Transact-SQL).

Caution

Když dotaz vrátí velké množství dat a volá BeginTransaction, vyvolá se SqlException, protože SQL Server neumožňuje paralelní transakce při použití MARS. Chcete-li se tomuto problému vyhnout, vždy přidružte transakci k příkazu, připojení nebo obojí před otevřením všech čtenářů.

Viz také

Platí pro

BeginTransaction(IsolationLevel, String)

Zdroj:
System.Data.SqlClient.notsupported.cs

Spustí databázovou transakci se zadanou úrovní izolace a názvem transakce.

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);
override this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel, transactionName As String) As SqlTransaction

Parametry

iso
IsolationLevel

Úroveň izolace, pod kterou má transakce běžet.

transactionName
String

Název transakce.

Návraty

Objekt představující novou transakci.

Výjimky

Paralelní transakce nejsou povoleny při použití více aktivních sad výsledků (MARS).

Paralelní transakce nejsou podporovány.

Příklady

Následující příklad vytvoří SqlConnection a .SqlTransaction Ukazuje také, jak používat BeginTransaction, a Commita Rollback metody.

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

Poznámky

Tento příkaz se mapuje na SQL Server implementaci BEGIN TRANSACTION.

Hodnotu v parametru transactionName lze použít v pozdějších voláních Rollback a v savePoint parametru Save metody.

Transakce musíte explicitně potvrdit nebo vrátit zpět pomocí Commit metody nebo Rollback metody. Abyste měli jistotu, že model správy transakcí SQL Server funguje správně, nepoužívejte jiné modely správy transakcí, jako je například model poskytovaný SQL Server.

Note

Jakmile je transakce potvrzena nebo vrácena zpět, úroveň izolace transakce přetrvává pro všechny následné příkazy, které jsou v režimu automatickéhocommit (SQL Server výchozí). To může vést k neočekávaným výsledkům, jako je například úroveň izolace funkce REPEATABLE READ, která se zachová a uzamkne ostatní uživatele mimo řádek. Pokud chcete obnovit výchozí úroveň izolace (READ COMMITTED), spusťte příkaz Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED nebo zavolejte SqlConnection.BeginTransaction následované okamžitě SqlTransaction.Commit. Další informace o úrovních izolace SQL Server najdete v tématu .

Další informace o transakcích SQL Server najdete v tématu Transactions (Transact-SQL).

Caution

Když dotaz vrátí velké množství dat a volá BeginTransaction, vyvolá se SqlException, protože SQL Server neumožňuje paralelní transakce při použití MARS. Chcete-li se tomuto problému vyhnout, vždy přidružte transakci k příkazu, připojení nebo obojí před otevřením všech čtenářů.

Viz také

Platí pro