【问题标题】:How can I use a variable as column name in mysql / express?如何在 mysql / express 中使用变量作为列名?
【发布时间】:2019-02-24 23:00:38
【问题描述】:

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

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() 适用于除列名之外的所有内容。

这就是我在注入变量后 console.log 查询得到的结果:

UPDATE scores
SET 'the name of my column' = 1
WHERE score_id = 1

【问题讨论】:

  • 我只是在我在这里写的例子中,而不是在我的实际代码中
  • 您是否在使用控制台日志或要打印的内容应用 const 后检查了 UpdateQuery?
  • 是的,我现在添加了它
  • 那么,问题出在单引号上!?
  • 是的,这就是导致问题的原因

标签: javascript mysql node.js express


【解决方案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.

【讨论】:

  • 谢谢 - 换掉?和 ??为我做的!
【解决方案2】:

Tamilvanan 解决方案稍作改动即可解决问题

 db.query(
            'UPDATE scores SET '+update+' = ? Where score_id = ?',
            [newValue, singleScore.score_id],
            (err, result) => {
              if (err) throw err;
              console.log(`Changed ${result.changedRows} row(s)`);
            }
          );

【讨论】:

    【解决方案3】:

    对于奇怪的 MySQL 列名,您不能在它们周围加上单引号。单引号只是将值转换为字符串。

    反引号在 MySQL 中用于此目的。例如

    UPDATE `table with space` SET `column with space` = 'bar';
    

    【讨论】:

    • 为了澄清这一点,在 MySQL 和大多数其他尝试至少部分遵守 SQL 标准的 RDBMS 中;即使对于非奇怪的列名,也不能在它们周围加上单引号。单引号仅用于分隔字符串。
    【解决方案4】:

    检查以下代码。它可能会起作用,

    con.query(
      'UPDATE scores SET '+update+' = ? Where score_id = ?',
      // Old - [${mysql.escape(newValue)}, ${mysql.escape(singleScore.score_id)}],
      /* Update - */ [newValue,singleScore.score_id],
      (err, result) => {
        if (err) throw err;
        console.log(`Changed ${result.changedRows} row(s)`);
      }
    );
    

    根据您的查询,${mysql.escape(update)} 包含值中的单引号。

    【讨论】:

    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2021-11-19
    • 1970-01-01
    • 2023-03-30
    • 2010-12-05
    相关资源
    最近更新 更多