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: