我正在尝试将城市数组传递给IN子句,但似乎在准备查询时将逗号分隔掉了
这是代码
let city = ["Moscow", "Paris"];
let sql = 'SELECT* FROM cities WHERE city IN ('+city+')';
console.log(sql);
在控制台中,我得到了
SELECT* FROM cities WHERE city IN (Moscow, Paris);
并因此在执行查询时出现异常!
有帮助吗?
答案 0 :(得分:1)
尝试一下,它将起作用
var sql = "SELECT uid FROM cities where city IN ('" + gender.join("','") + "')";
结果:-
SELECT uid FROM cities where city IN ('Male','Female')
答案 1 :(得分:1)
使用查询生成器是一种更可取的方法,但是如果您的数组很长,则可以使用以下解决方案:
let stringifiedValues = JSON.stringify(city).replace(/\[|\]/g,'');
let sql = `SELECT * FROM cities WHERE city IN (${stringifiedValues})`;
答案 2 :(得分:1)
Moscow
=> 'Moscow'
array.join(', ')
${str}
const city = ["Moscow", "Paris"];
const injectedString = city.map(c => `'${c}'`).join(', ');
let sql = `SELECT * FROM cities WHERE city IN (${injectedString})`;
console.log(sql);