問題描述
我正在 ADO.NET 中手動編寫事務代碼.我正在使用的示例重用了 SqlCommand
,這看起來是個好主意.
I'm coding a transaction manually in ADO.NET. The example I'm working from reuses the SqlCommand
which seem like a fine idea.
但是,我在命令中添加了參數(shù).
However, I have added parameters to my command.
我的問題是:在下面的代碼中,command.Parameters.Clear()
是否正確?還是我做錯了?
My question is: in the following code, is command.Parameters.Clear()
correct? Or am I doing it wrong?
using (var connection = new SqlConnection(EomAppCommon.EomAppSettings.ConnStr))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
foreach (var itemIDs in this.SelectedItemIds)
{
command.CommandText = "UPDATE Item SET payment_method_id = @batchID WHERE id in (@itemIDs)";
// IS THE FOLLOWING CORRECT?
command.Parameters.Clear();
command.Parameters.Add(new SqlParameter("@batchID", batchID));
command.Parameters.Add(new SqlParameter("@itemIDs", itemIDs));
command.ExecuteNonQuery();
}
transaction.Commit();
}
catch (Exception ex)
{
MessageBox.Show("Failed to update payment batches, rolling back." + ex.Message);
try
{
transaction.Rollback();
}
catch (Exception exRollback)
{
if (!(exRollback is InvalidOperationException)) // connection closed or transaction already rolled back on the server.
{
MessageBox.Show("Failed to roll back. " + exRollback.Message);
}
}
}
}
推薦答案
由于您重復執(zhí)行相同的查詢,因此沒有必要清除它們 - 您可以將參數(shù)添加到循環(huán)外,只需將它們填充到內即可.
Since you're repeatedly executing the same query, it's unnecessary to clear them - you can add the parameters outside the loop and just fill them inside.
try
{
command.CommandText = "UPDATE Item SET payment_method_id = @batchID WHERE id in (@itemIDs)";
command.Parameters.Add(new SqlParameter("@batchID", 0));
command.Parameters.Add(new SqlParameter("@itemIDs", ""));
foreach (var itemIDs in this.SelectedItemIds)
{
command.Parameters["@batchID"].Value = batchID;
command.Parameters["@itemIDs"].Value = itemIDs;
command.ExecuteNonQuery();
}
transaction.Commit();
}
注意 - 您不能在此處使用帶有 IN 的參數(shù) - 它不會工作.
Note - you can't use parameters with IN as you've got here - it won't work.
這篇關于重用帶有事務的 SqlCommand 時,我應該調用 Parameters.Clear 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!