C# Parameterized Query MySQL with `in` clause

前端 未结 7 1801
感情败类
感情败类 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: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#.

提交回复
热议问题