在多个数据库上实现事务

时间:2009-06-30 12:52:42

标签: .net sql-server database transactions

我正在多个数据库上执行数据更改,我想实现一个涵盖所有更改的事务。

这就是我目前所拥有的:

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 个答案:

答案 0 :(得分:12)

使用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类将自动转换为分布式事务。

答案 1 :(得分:1)

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

Transactions over multiple databases

答案 2 :(得分:0)

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

由于这取决于你没有提供任何细节的具体情况,我不能给你如何攻击它的想法。

答案 3 :(得分:0)

如果您希望跨多个SQL Server实例执行事务,请查看Microsoft Distributed Transaction Coordinator文档

相关问题