node mysql 查询错误,Node.js / MySQL:在node.js的错误日志中打印实际查询

"当在 Node.js 中使用连接池进行数据库查询时,可能会遇到错误导致打印的查询命令与实际执行的不一致。解决这个问题,可以利用 query 对象的 sql 属性来获取实际执行的 SQL 语句。例如,当执行 `connection.query(command, function(err, rows) {...}
摘要由CSDN通过智能技术生成

I have some Node.js code that tries to update a database in something like the following:

connection.query(command, function(err,rows) {

if (err){

console.log(command);

console.log("ERROR");

console.log(err);

return;

}

console.log("good");

});

The above is run repeatedly for different values of "command", thus generating different queries to the database. The problem is that when there is an error, the wrong query gets printed in the console.log(command). This is because the time the query is added to the queue, and the time the query is actually executed are not the same, so the value of "command" at each of these times isn't the same. Is there a way around this?

Note: console.log(err) prints the error itself, and also part of the query, but it only prints the line where the error occurred. I want to print the whole query.

解决方案

As per docs, You can use query.sql to get the actual executed query.

var post = {id: 1, title: 'Hello MySQL'};

var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {

// Neat!

});

console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

In this case, it will be

connection.query(command, function (err, rows) {

if (err) {

console.log('this.sql', this.sql); //command/query

console.log(command);

console.log("ERROR");

console.log(err);

return;

}

console.log("good");

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值