C# 如果发生错误, using 语句是否会回滚数据库事务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/641660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Will a using statement rollback a database transaction if an error occurs?
提问by mezoid
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()?
我在 using 语句中有一个 IDbTransaction,但我不确定如果在 using 语句中抛出异常,它是否会回滚。我知道 using 语句将强制调用 Dispose()...但是有谁知道 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?
更新:另外,我是否需要像下面那样显式调用 Commit() 或者这也会由 using 语句处理?
My code looks sort of like this:
我的代码看起来像这样:
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();
}
}
采纳答案by Sedat Kapanoglu
Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent.
事务类的 Dispose 方法执行回滚,而 Oracle 的类不执行。所以从事务的角度来看,它依赖于实现。
The using
statement for the connection object on the other hand would either close the connection to the database or return the connection to the pool after resetting it. In either case, the outstanding transactions should be rolled back. That's why an exception never leaves an active transaction lying around.
using
另一方面,连接对象的语句要么关闭与数据库的连接,要么在重置连接后将连接返回到池中。在任何一种情况下,都应该回滚未完成的事务。这就是为什么异常永远不会留下活动事务的原因。
Also, yes, you should call Commit()
explicitly.
另外,是的,您应该Commit()
明确调用。
回答by Tommy Hui
I believe that if there's an exception such that Commit()
was never called, then the transaction will automatically rollback.
我相信如果有一个Commit()
从未被调用过的异常,那么事务将自动回滚。
回答by jhale
You have to call commit. The using statement will not commit anything for you.
你必须调用提交。using 语句不会为您提交任何内容。