如何通过 Node.js 转义 MySQL 查询中的单引号(撇号)?

How to escape single quotations (apostrophes) in MySQL query through Node.js?

我正在制作一个程序,用户可以在其中将数据输入到网站的输入中。然后,此信息将使用 socket.io 中继回服务器,并存储在数据库中。我正在使用 this library 从 Node.js 访问 MySQL。通常,当用户输入数据时,就可以了。但是当数据包含单引号时,事情就不起作用了。这是一个例子:

let data = "LET'S GO"; 
// this is the data that the user inputs
// if it has single quotations in it, the code doesn't work
// otherwise it does

connection.getConnection(function(error, conn) {
  if (error) throw error; // if there's an error while connecting, throw it

  conn.query(
    `INSERT INTO table_name (column) VALUES ('${data}')`, // make query with this MySQL call
    function(err, result) {
      conn.release();
      if (err) throw err; // if there's an error with the call, throw it. Usually where my error comes
    }
  )
})

正如上面代码中的注释,如果 data 变量中有单引号, MySQL 将 return 出现如下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's go.' at line 1

最初 运行 遇到此错误后,我一直在寻找解决方案。在 this page 上,它说使用 mysql.escape()connection.escape()pool.escape() 来消除此问题。我查看了所有 Stack Overflow 解决方案,但它们似乎都指向这一点。此解决方案的问题是 data 被输入到 MySQL 查询中,周围有两个单引号。因此,查询看起来有点像这样:

INSERT INTO table_name (column) VALUES (''DATA_HERE'')

而不是:

INSERT INTO table_name (column) VALUES ('DATA_HERE')

此外,我已经查看了 mysql.escape()connection.escape()pool.escape() 的类似问题,但它们没有帮助,因为它们中的大多数没有直接解决方案。

如果这些单引号(撇号)出现在用户输入的 data 中,是否还有其他方法可以转义它们?

提前谢谢你。感谢您提供任何帮助。

好的,看来我找到了答案。我的 query 必须以类似于 prepared statements 的方式格式化(感谢@danblack)。应该这样做:

conn.query(
    `INSERT INTO table_name (column) VALUES (?)`,
    [data],
    function(err, result) {
      conn.release();
      if (err) throw err;
    }
)

我用 ? 替换了 '${data}',并且在 conn.query() 函数的下一个参数中,我给出了应该替换 ? 的值。

如果有多个数据值需要以类似的方式“转义”,您可以这样做:

conn.query(
    `INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)`,
    [data1, data2, data3],
    function(err, result) {
      conn.release();
      if (err) throw err;
    }
)

如果其他人碰巧有类似的悬而未决的问题,我希望这个答案。

注意: 这种“转义”方式不仅适用于 INSERT 语句。我相信它可以用于所有其他查询。