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

前端 未结 2 840
暗喜
暗喜 2020-12-19 07:21

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 p

相关标签:
2条回答
  • 2020-12-19 07:30

    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.

    0 讨论(0)
  • 2020-12-19 07:40

    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.

    0 讨论(0)
提交回复
热议问题