在多个数据库上实现事务 [英] Implementing transactions over multiple databases
本文介绍了在多个数据库上实现事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在多个数据库上执行数据更改,我想实现一个将覆盖所有更改的事务。
I am performing data changes on multiple databases, and I want to implement a transaction that will cover all of the changes.
这是我目前有的: / p>
This is what I currently have:
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()
(见注释)中发生异常。有没有更好的方法来完成这个?
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屋!
查看全文