将NodeJS变量输入到SQL查询中

时间:2019-03-22 00:03:45

标签: mysql node.js

我正在尝试获取mysql语句,以不给我错误。

声明:

app.get("/Getcompany", function(request, response) {
      let cname = request.query.cname
      var query = "select * from clientdata_nsw where companyname  = '" + connection.escape(cname) + "'"
      connection.query(query, function(err, rows) {
        if (err) {
          console.log(err);
          return;
        }
        rows.forEach(function(result) {
          console.log(result.companyname, result.service, result.phone, result.open_times, result.rating_facebook, result.rating_goggle)
        })

      });

错误消息:

Error: ER_PARSE_ERROR: 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 'ADBY IT​''' at line 1
    at Query.Sequence._packetToError (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\sequences\Sequence.js:51:14)
    at Query.ErrorPacket (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\sequences\Query.js:83:18)
    at Protocol._parsePacket (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\Protocol.js:280:23)
    at Parser.write (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\Parser.js:74:12)
    at Protocol.write (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\Connection.js:109:28)
    at Socket.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
    --------------------
    at Protocol._enqueue (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\protocol\Protocol.js:141:48)
    at Connection.query (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\mysql\lib\Connection.js:214:25)
    at C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\db.js:34:13
    at Layer.handle [as handle_request] (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\express\lib\router\index.js:275:10)
    at SendStream.error (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\serve-static\index.js:121:7)
    at SendStream.emit (events.js:189:13)
    at SendStream.error (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\send\index.js:270:17)
    at SendStream.onStatError (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\send\index.js:421:12)
    at next (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\send\index.js:736:16)
    at onstat (C:\Users\Adam.Wolarczuk\Desktop\Projects\nodetest\node_modules\send\index.js:725:14)
    at FSReqWrap.oncomplete (fs.js:153:21)
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlState: '42000',
  index: 0 }

3 个答案:

答案 0 :(得分:1)

  

格式错误,您需要先解决

app.get("/Getcompany", function(request, response) {

    let cname = request.query.cname

    var query = "select * from clientdata_nsw where companyname  = '" + connection.escape(cname) + "'"

    connection.query(query, function(err, rows) {
        if (err) {
            console.log(err);
            return;
        }

        rows.forEach(function(result) {
            console.log(result.companyname, result.service, result.phone, result.open_times, result.rating_facebook, result.rating_goggle)
        })

    });

});

如果您查看错误消息,说明您在错误地转义了变量。如果您发现尾随'ADBY IT​'''

,错误消息将非常有帮助
Error: ER_PARSE_ERROR: 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 'ADBY IT​'''

除了使用转义,您还可以使用?字符作为占位符,代表您希望这样逃避的值:

  • 数组变成列表,例如['a','b']转换为'a','b'

  • 嵌套数组变成分组列表(用于批量插入),例如 [['a','b'],['c','d']]变成('a','b'),('c','d')

  

示例:

let cname = request.query.cname;
let sql = mysql.format("SELECT * FROM clientdata_nsw WHERE companyname=?", [cname]);
connection.query(sql, function(err, rows) {
    if (err) {
       console.log(err);
          return;
       }
});

多个占位符以传递的相同顺序映射到值。例如,在以下查询中,foo等于a,bar等于b,baz等于c,而id将为userId:

connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function (error, results, fields) {
  if (error) throw error;
  // ...
});

引用并有用: https://github.com/mysqljs/mysql

答案 1 :(得分:1)

使用connection.escape()并添加您自己的单引号是没有意义的,因为它们最终都做同样的事情,并且一起使用意味着转义进行了两次。

如果您在下面浏览我的代码,您会注意到我已经使用template literals来避免通过附加较小的部分来构成主字符串的麻烦。 connection.escape()也将负责转义部分。我也想向您指出瑞安提到的票证,因为围绕connection.escape()

进行了讨论
app.get("/Getcompany", function(request, response) {
  const cname = request.query.cname, query = `select * from clientdata_nsw where companyname  = ${connection.escape(
    cname
  )}`;
  connection.query(query, function(err, rows) {
    if (err) {
      console.log(err);
      return;
    }

    rows.forEach(function(result) {
      console.log(
        result.companyname,
        result.service,
        result.phone,
        result.open_times,
        result.rating_facebook,
        result.rating_goggle
      );
    });
  });
});

答案 2 :(得分:-1)

使用connection.escape时,您不应提供自己的报价。这是您编写查询的方式:

var query = "select * from clientdata_nsw where companyname = " + connection.escape(cname)

您还可以像这样使用占位符:

connection.query('select * from clientdata_nsw where companyname = ?', [cname], 
    function(err, rows) {
      // ...
    }
);

此页面显示了如何使用connection.escape:https://www.w3resource.com/node.js/nodejs-mysql.php

顺便说一句,您不是第一个遇到这种困惑的人。有人为此行为开了罚单:

https://github.com/mysqljs/mysql/issues/594

他们解释说,由于数值不需要引号,因此添加引号的责任应由转义函数承担。