首页 > 解决方案 > 关于 sqlTransaction 操作的说明

问题描述

我对事务的理解是,它是一个或多个 SQL 命令,都将作为一个组执行。

现在,我正在阅读Microsoft 的文档,但我不明白第一个try-catch异常块的目标。如果事务失败,我们为什么要尝试回滚事务。我的意思是,如果它失败了,那么我们不应该肯定数据库中没有进行任何更改(因为这是事务的目标)?我不明白什么?

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)
        {
            // Logging exception details
            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // Logging exception details
            }
        }
    }
}

标签: c#sql

解决方案


或者查看system.transactions.transactionscope

它可以在 Using 中使用,如果未完成将回滚而无需回滚命令。


推荐阅读