Node.js / MySQL: printing the actual query in the Node.js error log

I have some Node.js code that is trying to update the database something like this:

connection.query(command, function(err,rows) { if (err){ console.log(command); console.log("ERROR"); console.log(err); return; } console.log("good"); }); 

The above is performed repeatedly for different values ​​of the "command", thereby generating different queries to the database. The problem is that when an error occurs in console.log(command) request is incorrect. This is due to the fact that the time of adding a request to the queue and the time of the actual execution of the request do not match, therefore the value of the command at each of these time points is not the same. Is there a way around this?

Note: console.log(err) prints the error itself, as well as part of the request, but prints only the line where the error occurred. I want to print the entire request.

+7
source share
2 answers

According to 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"); }); 
+19
source

If @Sridhar's answer does not work for you, perhaps because you are using the promise API, which does not yet return a SQL query , you can use:

 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

0
source

Source: https://habr.com/ru/post/1261348/


All Articles