C# Parameterized Query MySQL with `in` clause

前端 未结 7 1805
感情败类
感情败类 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: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 or a List 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(...));
    }
    

提交回复
热议问题