SqlConnection.BeginTransaction Metoda

Definicja

Uruchamia transakcję bazy danych.

Przeciążenia

Nazwa Opis
BeginTransaction()

Uruchamia transakcję bazy danych.

BeginTransaction(IsolationLevel)

Uruchamia transakcję bazy danych z określonym poziomem izolacji.

BeginTransaction(String)

Uruchamia transakcję bazy danych o określonej nazwie transakcji.

BeginTransaction(IsolationLevel, String)

Uruchamia transakcję bazy danych z określonym poziomem izolacji i nazwą transakcji.

BeginTransaction()

Uruchamia transakcję bazy danych.

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

Zwraca

Obiekt reprezentujący nową transakcję.

Wyjątki

Transakcje równoległe nie są dozwolone w przypadku korzystania z wielu aktywnych zestawów wyników (MARS).

Transakcje równoległe nie są obsługiwane.

Przykłady

Poniższy przykład tworzy element SqlConnection i .SqlTransaction Pokazuje również, jak używać BeginTransactionmetod , , Commiti Rollback .

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

Uwagi

To polecenie mapuje SQL Server implementację BEGIN TRANSACTION.

Musisz jawnie zatwierdzić lub wycofać transakcję przy użyciu Commit metody lub Rollback . Aby upewnić się, że Dostawca danych framework .NET dla modelu zarządzania transakcjami SQL Server działa prawidłowo, należy unikać używania innych modeli zarządzania transakcjami, takich jak SQL Server.

Note

Jeśli nie określisz poziomu izolacji, zostanie użyty domyślny poziom izolacji. Aby określić poziom izolacji z BeginTransaction metodą, użyj przeciążenia, które przyjmuje iso parametr (BeginTransaction). Poziom izolacji ustawiony dla transakcji będzie się powtarzać po zakończeniu transakcji i do momentu zamknięcia lub usunięcia połączenia. Ustawienie poziomu izolacji na Migawka w bazie danych, w której nie włączono poziomu izolacji migawki, nie zgłasza wyjątku. Transakcja zostanie ukończona przy użyciu domyślnego poziomu izolacji.

Ostrożność

Jeśli transakcja zostanie uruchomiona i na serwerze wystąpi błąd poziomu 16 lub wyższego, transakcja nie zostanie wycofana do momentu Read wywołania metody. W funkcji ExecuteReader nie jest zgłaszany żaden wyjątek.

Ostrożność

Gdy zapytanie zwraca dużą ilość danych i wywołuje BeginTransaction, zgłaszany jest SqlException, ponieważ SQL Server nie zezwala na równoległe transakcje podczas korzystania z usługi MARS. Aby uniknąć tego problemu, zawsze należy skojarzyć transakcję z poleceniem, połączeniem lub obydwoma elementami przed otwarciem dowolnego czytnika.

Aby uzyskać więcej informacji na temat transakcji SQL Server, zobacz Transactions (Transact-SQL).

Zobacz też

Dotyczy

BeginTransaction(IsolationLevel)

Uruchamia transakcję bazy danych z określonym poziomem izolacji.

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

Parametry

iso
IsolationLevel

Poziom izolacji, na którym powinna zostać uruchomiona transakcja.

Zwraca

Obiekt reprezentujący nową transakcję.

Wyjątki

Transakcje równoległe nie są dozwolone w przypadku korzystania z wielu aktywnych zestawów wyników (MARS).

Transakcje równoległe nie są obsługiwane.

Przykłady

Poniższy przykład tworzy element SqlConnection i .SqlTransaction Pokazuje również, jak używać BeginTransactionmetod , , Commiti Rollback .

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

Uwagi

To polecenie mapuje SQL Server implementację BEGIN TRANSACTION.

Musisz jawnie zatwierdzić lub wycofać transakcję przy użyciu Commit metody lub Rollback . Aby upewnić się, że Dostawca danych framework .NET dla modelu zarządzania transakcjami SQL Server działa prawidłowo, należy unikać używania innych modeli zarządzania transakcjami, takich jak SQL Server.

Note

Po zatwierdzeniu lub wycofaniu transakcji poziom izolacji transakcji będzie nadal występować dla wszystkich kolejnych poleceń, które są w trybie automatycznego zatwierdzeń (ustawienie domyślne SQL Server). Może to spowodować nieoczekiwane wyniki, takie jak poziom izolacji powtarzalnego odczytu utrwalającego i blokującego innych użytkowników z wiersza. Aby zresetować poziom izolacji do domyślnego (ODCZYT ZATWIERDZONY), wykonaj Transact-SQL USTAWIĆ POZIOM IZOLACJI TRANSAKCJI INSTRUKCJI READ COMMITTED lub wywołaj SqlConnection.BeginTransaction następnie natychmiast SqlTransaction.Commit. Aby uzyskać więcej informacji na temat poziomów izolacji SQL Server, zobacz Wyłączenie poziomów izolacji.

Aby uzyskać więcej informacji na temat transakcji SQL Server, zobacz Transactions (Transact-SQL).

Ostrożność

Gdy zapytanie zwraca dużą ilość danych i wywołuje BeginTransaction, zgłaszany jest SqlException, ponieważ SQL Server nie zezwala na równoległe transakcje podczas korzystania z usługi MARS. Aby uniknąć tego problemu, zawsze należy skojarzyć transakcję z poleceniem, połączeniem lub obydwoma elementami przed otwarciem dowolnego czytnika.

Zobacz też

Dotyczy

BeginTransaction(String)

Uruchamia transakcję bazy danych o określonej nazwie transakcji.

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

Parametry

transactionName
String

Nazwa transakcji.

Zwraca

Obiekt reprezentujący nową transakcję.

Wyjątki

Transakcje równoległe nie są dozwolone w przypadku korzystania z wielu aktywnych zestawów wyników (MARS).

Transakcje równoległe nie są obsługiwane.

Przykłady

Poniższy przykład tworzy element SqlConnection i .SqlTransaction Pokazuje również, jak używać BeginTransactionmetod , , Commiti Rollback .

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

Uwagi

To polecenie mapuje SQL Server implementację BEGIN TRANSACTION.

Długość parametru transactionName nie może przekraczać 32 znaków. W przeciwnym razie zostanie zgłoszony wyjątek.

Wartość w parametrze transactionName może być używana w kolejnych wywołaniach metody Rollback i w savePoint parametrze Save metody .

Musisz jawnie zatwierdzić lub wycofać transakcję przy użyciu Commit metody lub Rollback . Aby upewnić się, że Dostawca danych framework .NET dla modelu zarządzania transakcjami SQL Server działa prawidłowo, należy unikać używania innych modeli zarządzania transakcjami, takich jak SQL Server.

Aby uzyskać więcej informacji na temat transakcji SQL Server, zobacz Transactions (Transact-SQL).

Ostrożność

Gdy zapytanie zwraca dużą ilość danych i wywołuje BeginTransaction, zgłaszany jest SqlException, ponieważ SQL Server nie zezwala na równoległe transakcje podczas korzystania z usługi MARS. Aby uniknąć tego problemu, zawsze należy skojarzyć transakcję z poleceniem, połączeniem lub obydwoma elementami przed otwarciem dowolnego czytnika.

Zobacz też

Dotyczy

BeginTransaction(IsolationLevel, String)

Uruchamia transakcję bazy danych z określonym poziomem izolacji i nazwą transakcji.

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

Parametry

iso
IsolationLevel

Poziom izolacji, na którym powinna zostać uruchomiona transakcja.

transactionName
String

Nazwa transakcji.

Zwraca

Obiekt reprezentujący nową transakcję.

Wyjątki

Transakcje równoległe nie są dozwolone w przypadku korzystania z wielu aktywnych zestawów wyników (MARS).

Transakcje równoległe nie są obsługiwane.

Przykłady

Poniższy przykład tworzy element SqlConnection i .SqlTransaction Pokazuje również, jak używać BeginTransactionmetod , , Commiti Rollback .

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

Uwagi

To polecenie mapuje SQL Server implementację BEGIN TRANSACTION.

Wartość w parametrze transactionName może być używana w kolejnych wywołaniach metody Rollback i w savePoint parametrze Save metody .

Musisz jawnie zatwierdzić lub wycofać transakcję przy użyciu Commit metody lub Rollback . Aby upewnić się, że model zarządzania transakcjami SQL Server działa prawidłowo, należy unikać używania innych modeli zarządzania transakcjami, takich jak model udostępniony przez SQL Server.

Note

Po zatwierdzeniu lub wycofaniu transakcji poziom izolacji transakcji będzie nadal występować dla wszystkich kolejnych poleceń, które są w trybie automatycznego zatwierdzeń (ustawienie domyślne SQL Server). Może to spowodować nieoczekiwane wyniki, takie jak poziom izolacji powtarzalnego odczytu utrwalającego i blokującego innych użytkowników z wiersza. Aby zresetować poziom izolacji do domyślnego (ODCZYT ZATWIERDZONY), wykonaj Transact-SQL USTAWIĆ POZIOM IZOLACJI TRANSAKCJI INSTRUKCJI READ COMMITTED lub wywołaj SqlConnection.BeginTransaction następnie natychmiast SqlTransaction.Commit. Aby uzyskać więcej informacji na temat poziomów izolacji SQL Server, zobacz Wyłączenie poziomów izolacji.

Aby uzyskać więcej informacji na temat transakcji SQL Server, zobacz Transactions (Transact-SQL).

Ostrożność

Gdy zapytanie zwraca dużą ilość danych i wywołuje BeginTransaction, zgłaszany jest SqlException, ponieważ SQL Server nie zezwala na równoległe transakcje podczas korzystania z usługi MARS. Aby uniknąć tego problemu, zawsze należy skojarzyć transakcję z poleceniem, połączeniem lub obydwoma elementami przed otwarciem dowolnego czytnika.

Zobacz też

Dotyczy