Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
            }
        }
    }
}
like image 231
Aaron Anodide Avatar asked Jan 17 '13 08:01

Aaron Anodide


People also ask

What is SqlCommand parameters AddWithValue?

Use AddWithValue whenever you want to add a parameter by specifying its name and value. For SqlDbType Xml enumeration values, you can use a string, an XML value, an XmlReader derived type instance, or a SqlXml object.

What is the use of SqlCommand object explain three methods of it?

So, in short, we can say that the SqlCommand Object in C# is used to prepare the command text (T-SQL statement or Stored Procedure) that you want to execute against the SQL Server database and also provides some methods (ExecuteReader, ExecuteScalar, and ExecuteNonQuery) to execute those commands.

How does SqlCommand work in C#?

SqlCommand in C# allow the user to query and send the commands to the database. SQL command is specified by the SQL connection object. Two methods are used, ExecuteReader method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the method that is best for the different commands.

What is the SqlCommand object used for?

A SqlCommand object allows you to query and send commands to a database. It has methods that are specialized for different commands. The ExecuteReader method returns a SqlDataReader object for viewing the results of a select query. For insert, update, and delete SQL commands, you use the ExecuteNonQuery method.


2 Answers

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.

like image 73
Richard Avatar answered Sep 22 '22 06:09

Richard


In this condition you need it as you need set new parameters values, so its correct.

By the way, move

command.CommandText = ".."

outside of the loop too, as it's never changed.

like image 28
Tigran Avatar answered Sep 21 '22 06:09

Tigran