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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41169797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 22:07:05  来源:igfitidea点击:

Node.js/MySQL: Printing actual query in error log in node.js

mysqlnode.js

提问by user308485

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?

上面对不同的“command”值重复运行,从而对数据库产生不同的查询。问题是当出现错误时,错误的查询会打印在console.log(command). 这是因为查询加入队列的时间和查询实际执行的时间是不一样的,所以这些时间的“command”的值是不一样的。有没有解决的办法?

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)打印错误本身,也是查询的一部分,但它只打印发生错误的行。我想打印整个查询。

回答by Sridhar

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

根据docs,您可以使用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");
});

回答by Yves M.

If @Sridhar answerdoesn't work for you, probably because you are using promise API which doesn't yet return the SQL query, you can use:

如果@Sridhar 的回答对您不起作用,可能是因为您使用的是尚未返回 SQL 查询的promise API ,您可以使用:

const sql = connection.format("SELECT * FROM table WHERE foo = ?", ["bar"]);
console.log(sql);
const [rows] = await connection.query(sql);

Documentation: https://github.com/mysqljs/mysql#preparing-queries

文档:https: //github.com/mysqljs/mysql#preparing-queries