mysqlquery:使用一个列表来填充多个占位符



我想用javascript对我的数据库进行更新查询。对于这个查询,我想更新几行的一些'order_index'值。我正在尝试使用CASE函数并为when ? then ?部分使用变量来实现这一点。但是,行更改的数量可能会有所不同,因此我无法预先确定需要在查询中放入when ? then ?的次数。我的第一个解决方案是制作一个函数,将when ${id[x]} then ${index[x]}按适当的次数推入查询,但这是对sql注入敏感的。我试着将其调整为相同的,只是当时使用了占位符,但现在我不知道如何填充这些占位符,因为它可以是可变长度的。有没有一种方法可以使用单个值列表而不是多个分离的值来填充多个占位符?如果我没有用正确的方法来思考这个问题,那么这个问题的另一个解决方案也是受欢迎的。这里有一个我正在做的atm的例子:

const values = [];
for (let k in ids) {
values.push(` when '${ids[k]}' then  ${indices[k]}`);
}
const query = `UPDATE table1 SET order_index = (CASE id
${values.join(" ")}
else order_index
END)
WHERE other_id = ?`;
connection.query(query, other_id, function (error) {

这是我想做的东西:

const values = [];
const when_then_values = [];
for (let k in ids) {
values.push(` when ? then ?`);
when_then_values.push(ids[k]);
when_then_values.push(indices[k]);
}
const query = `UPDATE table1 SET order_index = (CASE id
${values.join(" ")}
else order_index
END)
WHERE other_id = ?`;
connection.query(query, [when_then_values, other_id], function (error) {

您想使用通用SQL库而不是sequelize之类的库有什么特别的原因吗?当您使用动态查询时,通常使用不只是用于纯原始SQL 的库是更好的选择

我发现,通过删除参数输入处的额外括号,可以用一个列表填充多个占位符。现在看起来是这样的:

const values = [];
const when_then_values = [];
for (let k in ids) {
values.push(` when ? then ?`);
when_then_values.push(ids[k]);
when_then_values.push(indices[k]);
}
when_then_values.push(other_id);
const query = `UPDATE table1 SET order_index = (CASE id
${values.join(" ")}
else order_index
END)
WHERE other_id = ?`;
connection.query(query, when_then_values, function (error) {

当然,查询中仍然有一个${values.join(" ")},但由于它只添加了一个带有占位符的预定义字符串,我认为这是可以的(?(。