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

时间:2021-01-07 00:13:25

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

我有一些node.js代码尝试更新数据库,如下所示:

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?

以上针对“命令”的不同值重复运行,从而对数据库生成不同的查询。问题是当出现错误时,会在console.log(命令)中打印错误的查询。这是因为查询添加到队列的时间以及查询实际执行的时间不同,因此每次这些时间的“命令”值都不相同。有没有解决的办法?

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.

注意:console.log(err)打印错误本身,也是查询的一部分,但它只打印发生错误的行。我想打印整个查询。

1 个解决方案

#1


16  

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

根据文档,您可以使用query.sql来获取实际执行的查询。

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");
});

#1


16  

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

根据文档,您可以使用query.sql来获取实际执行的查询。

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");
});