C# sqlclient数据库事务BeginTransaction,详解

重载

重载
BeginTransaction()

开始数据库事务。

BeginTransaction(IsolationLevel)

以指定的隔离级别启动数据库事务。

BeginTransaction(String)

以指定的事务名称启动数据库事务。

BeginTransaction(IsolationLevel, String)

以指定的隔离级别和事务名称启动数据库事务。

BeginTransaction()

开始数据库事务。

复制

public System.Data.SqlClient.SqlTransaction BeginTransaction ();

返回

SqlTransaction

表示新事务的对象。

例外

SqlException

使用多个活动结果集 (MARS) 时,不允许并行事务。

InvalidOperationException

不支持并行事务。

示例

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

注解

此命令映射到 BEGIN TRANSACTION 的 SQL Server 实现。

为了确保 SQL Server 事务管理模型的 .NET Framework 数据提供程序正确执行,请避免使用其他事务管理模型,如 SQL Server 提供的模型。

备注

该事务将使用默认隔离级别完成。

注意

ExecuteReader上不引发异常。

注意

若要避免此问题,请始终在打开任何读取器之前将事务与命令和/或连接关联。

https://docs.microsoft.com/zh-cn/dotnet/api/system.data.sqlclient.sqlconnection.begintransaction?view=dotnet-plat-ext-5.0