代码之家  ›  专栏  ›  技术社区  ›  Umair Ahmed

在多个数据库上执行事务

  •  6
  • Umair Ahmed  · 技术社区  · 17 年前

    try
    {
        db[1].begintransaction();
        db[1].ExecuteNonQuery();
    
        db[2].begintransaction();
        db[2].ExecuteNonQuery();
    
        ...
    
        db[N].begintransaction();
        db[N].ExecuteNonQuery();
    
        // will execute only if no exception raised during the process
        for (int a = 0; a < N; a++)
        {
            db[a].Commit();// what if there is an error/exception here
        }
    }
    catch
    {
        for (int a = 0; a < N; a++)
        {
            db[a].RollBack();
        }
    }
    

    Commit()

    4 回复  |  直到 13 年前
        1
  •  12
  •   Jesse    13 年前

    使用 TransactionScope 类如下:

    using (TransactionScope ts = new TransactionScope())
    {
        //all db code here
    
        // if an error occurs jump out of the using block and it will dispose and rollback
    
        ts.Complete();
    }
    

    如果需要,TransactionScope类将自动转换为分布式事务。

        2
  •  1
  •   Bill the Lizard    16 年前

    使用transactionScope就是答案。它甚至适用于不同的DBMS!!!

    Transactions over multiple databases

        3
  •  0
  •   Aaron Digulla    17 年前

    正如克莱图斯所说,你需要某种 two-phase commit 正如文章所述,这在实践中并不总是奏效。如果你需要一个健壮的解决方案,你必须找到一种方法来序列化事务,这样你就可以一个接一个地执行它们,并单独回滚它们。

    由于这取决于你没有提供任何细节的具体情况,我无法给你如何解决这个问题的想法。