我正在对多个数据库执行数据更改,并且我想实现一个涵盖所有更改的事务。
这就是我目前所拥有的:
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()
(见评论)。有没有更好的方法来实现这一点?
Use the 交易范围 http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx像这样的类:
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 类将自动转换为分布式事务。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)