【问题标题】:Implementing transactions over multiple databases在多个数据库上实现事务
【发布时间】:2009-06-30 12:52:42
【问题描述】:

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

这是我目前拥有的:

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() 期间发生异常,上述操作将严重失败(请参阅评论)。有没有更好的方法来做到这一点?

【问题讨论】:

  • 注意:这不是实际代码。为了清楚起见,我对其进行了重大修改
  • 嘿,我也遇到了同样的问题……我的数据库可以是 Mysql 和 Sql Server……它可以与 TransactionScope 一起使用吗?

标签: .net sql-server database transactions


【解决方案1】:

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

【讨论】:

  • @Jesse,我认为对于跨数据库的事务,即使在最新版本的 .Net 中,也需要 Microsoft 分布式事务协调器。我不明白你为什么说不需要它?
  • @Sunil 你是完全正确的。当时这是我对 .NET Framework 的误解。我将继续删除错误的评论。谢谢你通知我! =)
【解决方案2】:

使用 transactionScope 就是答案。它甚至可以与不同的 DBMS 一起使用!!!

Transactions over multiple databases

【讨论】:

    【解决方案3】:

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

    由于这取决于您未提供任何详细信息的具体案例,因此我无法为您提供如何解决此问题的想法。

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        • 2023-03-08
        • 1970-01-01
        • 2010-10-09
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多