实现了多个数据库的事务 [英] Implementing transactions over multiple databases

查看:700
本文介绍了实现了多个数据库的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表演上的多个数据库中的数据变化,我想实现,这将覆盖所有的变化的事务。

I am performing data changes on multiple databases, and I want to implement a transaction that will cover all of the changes.

这是我目前有:

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();
    }
}

问题是,上面会失败,可怕的,如果一个异常期间发生的一个提交()(见注释)。有没有实现这一点有什么好办法?

The problem is that the above would fail horribly if an exception happens during a Commit() (see the comment). Is there any better way of accomplishing this?

推荐答案

使用的这样的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类将自动转换为分布式事务,如果有必要的。

The TransactionScope class will automatically convert to a distributed transaction if necessary.

这篇关于实现了多个数据库的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆