views:

188

answers:

2

I am trying to do run a bulk deletion using parameterized queries. Currently, I have the following code:

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);

foreach (string name in selected)
    pendingDeletions.Parameters.AddWithValue("$name", name);

pendingDeletions.ExecuteNonQuery();

However, the value of the parameter seems to be overwritten each time and I end up just removing the last centre. What is the correct way to execute a parameterized query with a list of values?

+2  A: 
foreach (string name in selected) 
{
    pendingDeletions.Parameters.AddWithValue("$name", name);  <--
    pendingDeletions.ExecuteNonQuery(); 
}
Robert Harvey
Thanks. I've refactored my code to store a list of substitutions rather than a list of 'prepared' parameters, and I assign the values to the parameters while iterating through the queue as per your answer.
Rezzie
A: 

Rezzie, your current code is equivalent to:

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);


foreach (string name in selected)
{
    pendingDeletions.Parameters.AddWithValue("$name", centre.Name);
}

pendingDeletions.ExecuteNonQuery();

Which means you are only executing the query once, with the last value in your 'selected' enumerable.

This is the prime reason that I ALWAYS ALWAYS ALWAYS use block delimiters on conditionals and loops ALWAYS.

So, if you enclose the parameter assignment and the query execution in the loop you should be good to go.

pendingDeletions = new SQLiteCommand(@"DELETE FROM [centres] WHERE [name] = $name", conn);


foreach (string name in selected)
{
    pendingDeletions.Parameters.AddWithValue("$name", centre.Name);
    pendingDeletions.ExecuteNonQuery();
}
Sky Sanders
p.s. did i mention to **ALWAYS** enclose conditionals and loops? ;-)
Sky Sanders
Yes, I realised that the execution was outside of the loop - I'd (wrongly) assumed that I was building a list of substitutions to the command, when I was actually just overwriting a single substitution repeatedly.
Rezzie