The program is in C#, and I'm trying to pass a List<string>
as a parameter.
List<string> names = new List<string>{"john", "brian", "robert"};
In plain SQL, the query will look like this:
DELETE FROM Students
WHERE name = 'john' or name = 'brian' or name = 'robert'
When running a SQL command in C# code, I know that the proper way of doing it is to use parameters instead of concatenating everything into one giant string.
command.CommmandText = "DELETE FROM Students WHERE name = @name";
command.Parameters.Add(new MySqlParameter("@name", String.Format("'{0}'", String.Join("' or name = '", names)));
command.NonQuery();
The above method did not work. It didn't throw any error/exception, it just simply didn't work the way I want it to.
How should I go about doing this?
I thought about looping through the List<string>
and just execute on every single name.
foreach(string name in names)
{
command.CommmandText = "DELETE FROM Students WHERE name = @name";
command.Parameters.Add(new MySqlParameter("@name", name));
command.NonQuery();
command.Parameters.Clear();
}
But this will take a long time as the actual List<string>
is quite large. I want to try execute at little as possible.
Thanks!
You can parameterize each value in the list in an IN
clause:
List<string> names = new List<string> { "john", "brian", "robert" };
string commandText = "DELETE FROM Students WHERE name IN ({0})";
string[] paramNames = names.Select(
(s, i) => "@tag" + i.ToString()
).ToArray();
string inClause = string.Join(",", paramNames);
using (var command = new SqlCommand(string.Format(commandText, inClause), con))
{
for (int i = 0; i < paramNames.Length; i++)
{
command.Parameters.AddWithValue(paramNames[i], names[i]);
}
int deleted = command.ExecuteNonQuery();
}
which is similar to:
"... WHERE Name IN (@tag0,@tag1,@tag2)"
command.Parameters["@tag0"].Value = "john";
command.Parameters["@tag1"].Value = "brian";
command.Parameters["@tag2"].Value = "robert";
Adapted from: https://stackoverflow.com/a/337792/284240
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With