Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - Should I call Parameters.Clear when reusing a SqlCommand with a transation?

I'm coding a transaction manually in ADO.NET. The example I'm working from reuses the SqlCommand which seem like a fine idea.

However, I have added parameters to my command.

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);
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

Note - you can't use parameters with IN as you've got here - it won't work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...