[英]Using using() blocks during ADO.NET transaction
我需要進行一個相對瑣碎的事務,但是這會影響5-6個表,因此我遍歷了一些有關如何執行此操作的教程,因為我以前從未使用過事務,因此我將每個新查詢都包裝在using(...)
塊:
SqlTransaction transaction = null;
SqlConnection connection = null;
string localConnString =System.Web.Configuration.WebConfigurationManager..;
try
{
connection = new SqlConnection(localConnString);
connection.Open();
string insertSomeValues = "some SQL INSERT query"..
using (SqlCommand command = new SqlCommand(insertSomeValues, connection))
{
..
}
using(SqlCommand newCommand = new SqlCommand(otherQuery, connection))
{
..
}
transaction.Commit();
}
catch
{
transaction.Rollback();
}
finally
{
connection.Close();
}
所以我希望你有主意。 我認為此實現存在的問題是,由於using
塊位於pricatice中,因此如果仍然沿途執行其他代碼的某個地方引發了異常,則try-catch
塊會被執行,更重要的是transaction.Commit();
太。 這使事務無用,因為當我需要事務(全部或全部)時,我最終會得到部分更改的database
。
由於缺乏有關該主題的經驗,我想知道如何正確處理此類情況。 在一個示例中,有一個bool
標志,指示當前操作的進行方式以及調用transaction.Commit();
之前的操作transaction.Commit();
有某種檢查:
if (!hasErrors)
{
transaction.Commit();
}
但由於我在事務中包含服務器表,並且有一些查詢用於獲取信息或檢查某些內容,因此使用標志的想法不是很誘人。 我正在考慮刪除using()
塊,以便(至少我認為那是應該發生的)每當引發錯誤時,我都會直接轉到主catch塊。 所以..有一些想法,但是處理這個問題的實際方法是什么?
我已經修改了您的代碼,包括所有命令的通用事務處理。
SqlTransaction transaction = null;
SqlConnection connection = null;
string localConnString =System.Web.Configuration.WebConfigurationManager..;
try
{
connection = new SqlConnection(localConnString);
connection.Open();
transaction=connection.BeginTransaction();
string insertSomeValues = "some SQL INSERT query"..
using (SqlCommand command = new SqlCommand(insertSomeValues, connection,transaction))
{
..
}
using(SqlCommand newCommand = new SqlCommand(otherQuery, connection,transaction))
{
..
}
transaction.Commit();
}
catch
{
transaction.Rollback();
}
finally
{
connection.Close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.