node中同时执行多条语句的坑

文章类型:node

发布者:hp

发布时间:2023-04-30

在使用node+mysql实现开发过程中,需求会涉及到查询多个结果,如果采取一条sql查询一次,太过浪费和繁琐

一:使用方式

 const  sql=`SELECT d,MAX(total) as max FROM
(SELECT DATE_FORMAT(times,'%y年%m月%d日') as d , count(*) as total
FROM statistics
GROUP BY DATE_FORMAT(times,'%y%m%d') DESC ) as tem; SELECT COUNT(*) as total, SUM(num) as allnum FROM statistics `

console.log(sql)
db.query(sql ,(error, results) => {
console.log(error)
console.log(results)
res.send({
code: "200",
message: "查询统计分类成功",
data:results
});
});

然后遇到错误,但是sql语句通过其他运行正常

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

二:解决方案,因为考虑到安全防止注入的原因,默认关闭了多语句查询导致,我们需要手动将multipleStatements设置为true

mysql.createPool({
host: "127.0.0.1", //这是数据库的地址
user: "root", //需要用户的名字
password: "root", //用户密码 ,如果你没有密码,直接双引号就是
multipleStatements:true,
database: "blogs" //数据库名字

就可以了

[
[ RowDataPacket { d: '23年04月29日', max: 18 } ],
[ RowDataPacket { total: 199, allnum: 1051 } ]
]