首页 > 解决方案 > 在查询字符串中传递多个 id,并在节点 js 中的 mysql 中为它们获取数据

问题描述

我在 nodejs 中有一个 get API,它获取变量字符串作为查询字符串(由“,”分隔),如下所示

const mac = req.query.mac; 
console.log(mac); // 00:11:22:33:FF:EE,11:11:22:33:FF:EE
var sql =  mysql.format("SELECT * FROM user_email WHERE macId IN ?",[mac]);
        connection.query(sql, function(err, row) ...{ ... .. }

但我收到错误

code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''00:11:22:33:FF:EE,11:11:22:33:FF:EE'' at line 1",
  sqlState: '42000',
  index: 0,
  sql: "SELECT * FROM user_email WHERE macId IN '00:11:22:33:FF:EE,11:11:22:33:FF:EE'"
}

有人请帮助!

标签: mysqlnode.js

解决方案


您的错误是将 mac 从字符串转换为数组

[mac]

不会将其转换为字符串。试试这个:

const mac = req.query.mac; 
const macArr = mac.split(',');
var sql =  mysql.format("SELECT * FROM user_email WHERE macId IN (?)", macArr);
connection.query(sql, function(err, row) ...{ ... .. }

推荐阅读