node-postgres: how to execute “WHERE col IN ()” query?

后端 未结 7 615
梦毁少年i
梦毁少年i 2020-11-28 06:02

I\'m trying to execute a query like this:

SELECT * FROM table WHERE id IN (1,2,3,4)

The problem is that the list of ids I want to filter ag

7条回答
  •  余生分开走
    2020-11-28 06:21

    We've seen this question before on the github issues list. The correct way is to dynamically generate your list of parameters based on the array. Something like this:

    var arr = [1, 2, "hello"];
    var params = [];
    for(var i = 1; i <= arr.length; i++) {
      params.push('$' + i);
    }
    var queryText = 'SELECT id FROM my_table WHERE something IN (' + params.join(',') + ')';
    client.query(queryText, arr, function(err, cb) {
     ...
    });
    

    That way you get the postgres parameterized escaping.

提交回复
热议问题