目前我有这个问题,问题是表名有一组引号(它是一个字符串),这会导致服务器崩溃。
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ${mysql.escape(update)} = ${mysql.escape(newValue)}
WHERE score_id = ${mysql.escape(singleScore.score_id)}`;
mysql.escape()
适用于除列名之外的所有内容。
如果我在注入(inject)变量后对查询进行 console.log,这就是我得到的结果:
UPDATE scores
SET 'the name of my column' = 1
WHERE score_id = 1
最佳答案
看起来您正在使用 mysql NPM package .
escape
方法用于转义查询值。要转义查询标识符(如列名),您应该改用 escapeId
方法。您的代码应如下所示:
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ${mysql.escapeId(update)} = ${mysql.escape(newValue)}
WHERE score_id = ${mysql.escape(singleScore.score_id)}`;
同样,如果您使用替换,请使用双问号而不是单个问号来转义标识符。
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ?? = ?
WHERE score_id = ?`;
const replacements = [update, newValue, singleScore.score_id];
关于javascript - 如何在 mysql/express 中使用变量作为列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52428398/