加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

.net – 在多个数据库上实现事务

发布时间:2020-12-12 07:49:09 所属栏目:MsSql教程 来源:网络整理
导读:我正在多个数据库上执行数据更改,我想实现一个涵盖所有更改的事务. 这就是我目前拥有的: try{ db[1].begintransaction(); db[1].ExecuteNonQuery(); db[2].begintransaction(); db[2].ExecuteNonQuery(); ... db[N].begintransaction(); db[N].ExecuteNonQue
我正在多个数据库上执行数据更改,我想实现一个涵盖所有更改的事务.

这就是我目前拥有的:

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()期间发生异常,上述情况将会非常失败(请参阅注释).有没有更好的方法来实现这一目标?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读