19

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.

4 Answers 4

40

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");
});
3
  • 2
    didn't work for me. throw err; // Rethrow non-MySQL errors ^ ReferenceError: query is not defined Commented Sep 5, 2018 at 12:12
  • 1
    @SudhirKGupta you should use normal function instead of arrow functions
    – Sridhar
    Commented Sep 5, 2018 at 12:52
  • @Sridhar, I didn't get you. may you provide a sample code please? Commented Sep 6, 2018 at 6:35
15

If @Sridhar answer doesn't work for you, probably because you are using promise API which doesn't yet return the 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
let SqlString = require('sqlstring'); //global declare
let sql = "select * from abc where id = ? and name = ?"
const params_list = [5, "aaa"];

console.log('sql: ', SqlString.format(sql, params_list));

this is a complete scenario to print formatted SQL queries with parameters.

0

Best answer here can be like this This is for vscode only

Run code in debug mode Put debug point in if(err) block type following in debug console

copy(error.sql)

It will give you exact query . Hope it will help

Not the answer you're looking for? Browse other questions tagged or ask your own question.