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!
name = @n1 or name= @n2 or name = @n3
to the query and create all the parameters. UsingIn
makes for more concise code, but the main point is that you need more than one parameter here. – Hardball