javascript - 如何在 mysql/express 中使用变量作为列名?

标签 javascript mysql node.js express

目前我有这个问题,问题是表名有一组引号(它是一个字符串),这会导致服务器崩溃。

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];

See the mysql docs for more details.

关于javascript - 如何在 mysql/express 中使用变量作为列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52428398/

相关文章:

javascript - html 链接更改页面或只是动态更新页面?

mysql - 无法在 Java 中将 ' 插入到我的 MySQL 数据库中

node.js - Nest.js 在 Passport 本地策略中获取请求头

javascript - 如何动态添加多个HTTP header

javascript - ng-model - 空输入返回 null

javascript - 如何改进正则表达式,使其可以匹配 google script 电子邮件抓取工具的电子邮件格式?

mysql - 重置 insert into 语句中的 auto_increment

mysql - SQL : How to update table Automatically in 2nd database when table in 1st database is updated?

javascript - 从 javascript 中调用快速路由

node.js - 在 CNAME 重定向之前拦截流量