C# Parameterized Query MySQL with `in` clause

前端 未结 7 1781
感情败类
感情败类 2020-12-03 15:36

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 part

相关标签:
7条回答
  • 2020-12-03 16:15

    You cannot use parameters for an IN clause.

    0 讨论(0)
  • 2020-12-03 16:17

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

    0 讨论(0)
  • 2020-12-03 16:20

    Since MySQL 4.0 you can use FIND_IN_SET function to create parametrized SQL with 'in clause'.

    Your code:

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

    Changed to use FIND_IN_SET:

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

    Finally you can use variables to parametrize your query:

    var s = "UPDATE TABLE_1 SET STATUS = 4 WHERE FIND_IN_SET(ID, ?)";
    var params = "1, 14, 145, 43";
    
    dataSource.Execute(s, params);
    

    See the W3Schools reference and the MySQL Tutorial

    Since FIND_IN_SET is a MySQL function it works with every language not just C#.

    0 讨论(0)
  • 2020-12-03 16:21

    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

    0 讨论(0)
  • 2020-12-03 16:30

    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(...));
    }
    
    0 讨论(0)
  • 2020-12-03 16:33

    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.

    0 讨论(0)
提交回复
热议问题