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



我正在制作一个程序,用户可以在该程序中将数据输入到网站上的输入中。然后,这些信息将使用socket.io中继回服务器,并存储在数据库中。我使用这个库从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将返回如下错误:

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

在最初遇到这个错误后,我一直在寻找解决方案。在这个页面上,它说使用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语句。我相信它可以用于所有其他查询。

最新更新