删除节点js mysql查询中的斜杠

时间:2015-11-06 07:18:37

标签: javascript mysql sql node.js

这是我的代码。

pool.getConnection(function (err, connection) {
        connection.query("delete from userFiles where type = 1 and 
                          typeId = " + taskId + " and fileName 
                          NOT IN ('?') ",[oldFileNames], function (err, rows) {

        });
    });

现在的问题是,节点js正在生成这样的查询,

delete from table_name where type = 1 and typeId = 1 and 
fileName NOT IN (\'\'upload_149f2b78e5fd4096781bb5b8719b874f.png,upload_e8185e896cb0f8bb0b66d807cc60922c.png\'\')

我甚至试过这样,

connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " and
                    fileName NOT IN ('" + oldFileNames + "') ", 
                      function (err, rows) {

这样生成的查询就像这样,

delete from userFiles where type = 1 and typeId = 1 and 
fileName NOT IN (\'upload_149f2b78e5fd4096781bb5b8719b874f.png,
upload_e8185e896cb0f8bb0b66d807cc60922c.png\')

两者都导致查询出现mysql语法错误(斜杠被追加)。

你能建议我能做些什么来消除这个错误。

2 个答案:

答案 0 :(得分:3)

您不应该在?占位符周围添加引号。删除它们。

您还应传递数组,而不是字符串。假设它是一个干净的字符串,你可以使用split

connection.query(
      "delete from userFiles where type = 1 and typeId = " + taskId +
      " and fileName NOT IN (?) ", [oldFileNames.split(/,\s*/)],
      function (err, rows) {

答案 1 :(得分:1)

一种可能的解决方案是使用connection.escape();

connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " 
and fileName NOT IN (" + connection.escape(oldFileNames) + ")");