0

I use node.js and the module node-mysql for connecting to the mySQL server. However, I got some problems when I tried to escape an array in a query. Here is my code:

connection.query("select * from table where id in (?)", [1, 3, 5], function(err, res) {
    ...
});

The above query is select * from table where id in (1), which is not my expectation.

As the documents said:

Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'

I know select * from table where id in (?,?,?) works. The question is, what should I do if I have an array with unknown length?

1 Answer 1

7

One solution is to nest the array so that it gets properly converted to a list:

connection.query("select * from table where id in (?)", [[1, 3, 5]], ...);

Another solution would be to dynamically generate the ?s. For example:

var values = [1, 3, 5];
var query = "select * from table where id in ("
            + new Array(values.length + 1).join('?,').slice(0, -1)
            + ")";
connection.query(query, values, function(err, res) {
    ...
});

With ES6, you can simplify the list creation in the second solution to:

'?,'.repeat(values.length).slice(0, -1)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. I know I can generate numbers of ? base on length on the array, which is pure javascript approach. I am looking for some higher level solutions. I will use your method if there is no better way.
i had the same id using lodash functions: _.times(ids.length, _.constant('?')).join(). and then passing the array like: query(query, ids, function...). But your approach is much cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.