C# Parameterized Query MySQL with `in` clause

安稳与你 提交于 2019-12-17 16:31:35

问题


I am in the process of converting several queries which were hard-coded into the application and built on the fly to parameterized queries. I'm having trouble with one particular query, which has an in clause:

UPDATE TABLE_1 SET STATUS = 4 WHERE ID IN (1, 14, 145, 43);

The first parameter is easy, as it's just a normal parameter:

MySqlCommand m = new MySqlCommand("UPDATE TABLE_1 SET STATUS = ? WHERE ID IN (?);");
m.Parameters.Add(new MySqlParameter("", 2));

However, the second parameter is a list of integers representing the ids of the rows that need updating. How do I pass in a list of integers for a single parameter? Alternatively, how would you go about setting up this query so that you don't have to completely build it each and every time you call it, and can prevent SQL injection attacks?


回答1:


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(...));
}



回答2:


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.




回答3:


You cannot use parameters for an IN clause.




回答4:


Old question, but in case anyone comes across this via Google, here's what I use:

int status = 4;  
string ids = "1,14,145,43";      

m.Parameters.AddWithValue("@Status", status);
m.Parameters.AddWithValue("@IDs", ids);

UPDATE TABLE_1 SET STATUS = @Status WHERE FIND_IN_SET(ID, @IDs) > 0;

Note: FIND_IN_SET is a mySQL specific function.

Credit, where credit is due: See this question: Add List<int> to a mysql parameter




回答5:


Loop round your list of integers and perform individual updates.

MSSQL 2008 offers table-valued parameters to avoid this issue, I'm not aware of any similar functionality in MySQL.




回答6:


i'd suggest creating a function (assuming that mysql supports user defined functions) to break the parameter apart to return a table.



来源:https://stackoverflow.com/questions/650455/c-sharp-parameterized-query-mysql-with-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!