wde*_*tac 0 javascript node.js node-mysql
我使用 node.js 和模块 node-mysql 连接到 mySQL 服务器。但是,当我尝试在查询中转义数组时遇到了一些问题。这是我的代码:
connection.query("select * from table where id in (?)", [1, 3, 5], function(err, res) {
...
});
Run Code Online (Sandbox Code Playgroud)
上面的查询是select * from table where id in (1),这不是我的期望。
正如文件所说:
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
我知道select * from table where id in (?,?,?)有效。问题是,如果我有一个长度未知的数组,我该怎么办?
一种解决方案是嵌套数组,以便将其正确转换为列表:
connection.query("select * from table where id in (?)", [[1, 3, 5]], ...);
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是动态生成?s。例如:
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) {
...
});
Run Code Online (Sandbox Code Playgroud)
使用 ES6,您可以将第二个解决方案中的列表创建简化为:
'?,'.repeat(values.length).slice(0, -1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1306 次 |
| 最近记录: |