c# – 如果发生错误,using语句是否会回滚数据库事务?
c# – 如果发生错误,using语句是否会回滚数据库事务?
问题:
我在using语句中有一个IDbTransaction,但我不确定如果在using语句中抛出异常,它是否会被回滚。 我知道using语句会强制调用Dispose()……但是有人知道Rollback()是否也是如此?
更新:此外,我是否需要显式调用Commit(),如下所示,还是由using语句处理吗?
我的代码看起来像这样:
using Microsoft.Practices.EnterpriseLibrary.Data;
...
using(IDbConnection connection = DatabaseInstance.CreateConnection())
{
connection.Open();
using(IDbTransaction transaction = connection.BeginTransaction())
{
//Attempt to do stuff in the database
//potentially throw an exception
transaction.Commit();
}
}
I’ve got an IDbTransaction in a using statement but I’m unsure if it will be rolled back if an exception is thrown in a using statement.I know that a using statement will enforce the calling of Dispose()…but does anyone know if the same is true for Rollback()?Update: Also, do I need to call Commit() explicitly as I have below or will that also be taken care of by the using statement?My code looks sort of like this:
解决方案:
方案1:
事务类的Dispose方法执行回滚,而Oracle的类没有。 因此从事务的角度来看,它依赖于实现。
另一方面,连接对象的using
语句将关闭与数据库的连接,或者在重置后将连接返回到池。 在任何一种情况下,都应该回滚未完成的交易。 这就是为什么异常永远不会留下积极的交易。
此外,是的,您应该显式调用Commit()
。
方案2:
你必须调用commit。 using语句不会为您提交任何内容。
方案3:
我相信如果有一个例外,从未调用过Commit()
,那么事务将自动回滚。