用 TransactionScope 来实现事务

// This function takes arguments for 2 connection strings and commands to create a transaction 
// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the 
// transaction is rolled back. To test this code, you can connect to two different databases 
// on the same server by altering the connection string, or to another 3rd party RDBMS by 
// altering the code in the connection2 code block.
static public int CreateTransactionScope(
    string connectString1, string connectString2,
    string commandText1, string commandText2)
{
    // Initialize the return value to zero and create a StringWriter to display results.
    int returnValue = 0;
    System.IO.StringWriter writer = new System.IO.StringWriter();

    try
    {
        // Create the TransactionScope to execute the commands, guaranteeing
        // that both commands can commit or roll back as a single unit of work.
        using (TransactionScope scope = new TransactionScope())
        {
            using (SqlConnection connection1 = new SqlConnection(connectString1))
            {
                // Opening the connection automatically enlists it in the 
                // TransactionScope as a lightweight transaction.
                connection1.Open();

                // Create the SqlCommand object and execute the first command.
                SqlCommand command1 = new SqlCommand(commandText1, connection1);
                returnValue = command1.ExecuteNonQuery();
                writer.WriteLine("Rows to be affected by command1: {0}", returnValue);

                // If you get here, this means that command1 succeeded. By nesting
                // the using block for connection2 inside that of connection1, you
                // conserve server and network resources as connection2 is opened
                // only when there is a chance that the transaction can commit.   
                using (SqlConnection connection2 = new SqlConnection(connectString2))
                {
                    // The transaction is escalated to a full distributed
                    // transaction when connection2 is opened.
                    connection2.Open();

                    // Execute the second command in the second database.
                    returnValue = 0;
                    SqlCommand command2 = new SqlCommand(commandText2, connection2);
                    returnValue = command2.ExecuteNonQuery();
                    writer.WriteLine("Rows to be affected by command2: {0}", returnValue);
                }
            }

            // The Complete method commits the transaction. If an exception has been thrown,
            // Complete is not  called and the transaction is rolled back.
            scope.Complete();

        }

    }
    catch (TransactionAbortedException ex)
    {
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    }
    catch (ApplicationException ex)
    {
        writer.WriteLine("ApplicationException Message: {0}", ex.Message);
    }

    // Display messages.
    Console.WriteLine(writer.ToString());

    return returnValue;
}

来源:点击打开链接

在实例化 TransactionScope 后(通过new 语句),事务管理器确定哪些事务参与进来。一旦确定,该范围将始终参与该事务。 此决策基于两个因素:是否存在环境事务以及构造函数中TransactionScopeOption 参数的值。您的代码是在环境事务中执行的。 可通过调用 Transaction 类的静态Current 属性获取对环境事务的引用。有关如何使用此参数的更多信息,请参见Implementing An Implicit Transaction Using Transaction Scope 主题的“事务流管理”一节。

如果在事务范围中(即从初始化 TransactionScope 对象到调用其 Dispose 方法之间)未发生异常,则允许该范围所参与的事务继续。如果事务范围中的确发生了异常,它所参与的事务将回滚。

当应用程序完成它要在一个事务中执行的所有工作以后,您应当只调用 Complete 方法一次,以通知事务管理器可以接受提交事务。未能调用此方法将中止该事务。

Dispose 方法的调用标志着该事务范围的结束。在调用此方法之后发生的异常不会影响该事务。

如果在范围中修改 Current 的值,则会在调用Dispose 时引发异常。但是,在该范围结束时,先前的值将被还原。 此外,如果在创建事务的事务范围内对 Current 调用Dispose,则该事务将在相应范围末尾处中止。

——————   ————————   ———————————   ——————————   ———————

简单一点来说, 也就是在其定义的范围之内, 如果有异常则自动回滚, 没有异常就执行了。 见上面的红字。

这种做法, 比 SqlTranscation 来得更简洁更方便——无需显式地回滚。

在 catch 中加入 returnValue = 0 ; 即可判断其执行是否有回滚。 

因为代码段本身就在 using 之中, 所以无需执行 scope.Dispose();

不经常看msdn, 就不是一个合格的程序员。


不过, 另有一篇文章称 TrascationScope 在并发量大的情况下, 容易产生死锁, 见:

点击打开链接


此外, 还有一个针对事务出现错误执行的例子:点击打开链接

此例说明了, 关于事务处理, 连接打开一定要放在事务处理之内!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的使用TransactionScope的代码示例,用于演示如何将多个数据库操作包装在一个事务中: ``` using System; using System.Data.SqlClient; using System.Transactions; class Program { static void Main() { // 创建一个连接字符串 string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True"; // 创建一个事务范围对象 using (TransactionScope scope = new TransactionScope()) { try { // 执行第一个数据库操作 using (SqlConnection connection1 = new SqlConnection(connectionString)) { connection1.Open(); SqlCommand command1 = new SqlCommand("INSERT INTO Customers (Name) VALUES ('Customer 1')", connection1); command1.ExecuteNonQuery(); } // 执行第二个数据库操作 using (SqlConnection connection2 = new SqlConnection(connectionString)) { connection2.Open(); SqlCommand command2 = new SqlCommand("INSERT INTO Orders (CustomerId, OrderDate) VALUES ((SELECT TOP 1 Id FROM Customers ORDER BY Id DESC), GETDATE())", connection2); command2.ExecuteNonQuery(); } // 提交事务 scope.Complete(); } catch (Exception ex) { // 回滚事务 Console.WriteLine("Transaction rolled back: " + ex.Message); } } } } ``` 在这个示例中,我们使用了TransactionScope类来创建一个事务范围,然后在这个范围内执行了两个数据库操作。如果两个操作都成功执行,我们调用了TransactionScope的Complete方法来提交事务。如果其中任何一个操作失败,我们就会在catch块中回滚事务

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值