問題描述
我在 using 語句中有一個 IDbTransaction,但我不確定如果在 using 語句中拋出異常,它是否會回滾.我知道 using 語句將強制調用 Dispose()...但是有誰知道 Rollback() 是否也是如此?
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()?
更新:另外,我是否需要像下面那樣顯式調用 Commit() 或者這也會由 using 語句處理?
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:
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();
}
}
推薦答案
事務類的 Dispose 方法執行回滾,而 Oracle 的類不執行.因此,從事務的角度來看,它依賴于實現.
Dispose method for transaction class performs a rollback while Oracle's class doesn't. So from transaction's perspective it's implementation dependent.
另一方面,連接對象的 using
語句要么關閉與數據庫的連接,要么在重置連接后將連接返回到池中.無論哪種情況,都應該回滾未完成的事務.這就是為什么異常永遠不會留下活動事務的原因.
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.
另外,是的,您應該顯式調用 Commit()
.
Also, yes, you should call Commit()
explicitly.
這篇關于如果發生錯誤, using 語句是否會回滾數據庫事務?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!