C# Parameterized Query MySQL With `in` Clause


Answer :

This is not possible in MySQL. You can create a required number of parameters and do UPDATE ... IN (?,?,?,?). This prevents injection attacks (but still requires you to rebuild the query for each parameter count).

Other way is to pass a comma-separated string and parse it.


You could build up the parametrised query "on the fly" based on the (presumably) variable number of parameters, and iterate over that to pass them in.

So, something like:

List foo; // assuming you have a List of items, in reality, it may be a List<int> or a List<myObject> with an id property, etc.  StringBuilder query = new StringBuilder( "UPDATE TABLE_1 SET STATUS = ? WHERE ID IN ( ?") for( int i = 1; i++; i < foo.Count ) {   // Bit naive      query.Append( ", ?" ); }  query.Append( " );" );  MySqlCommand m = new MySqlCommand(query.ToString()); for( int i = 1; i++; i < foo.Count ) {     m.Parameters.Add(new MySqlParameter(...)); } 

You cannot use parameters for an IN clause.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?