如果发生错误,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();
}
}
34705 次浏览

Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent.

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.

Also, yes, you should call Commit() explicitly.

I believe that if there's an exception such that Commit() was never called, then the transaction will automatically rollback.

You have to call commit. The using statement will not commit anything for you.