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

前端 未结 2 579
闹比i
闹比i 2020-12-24 08:20

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){
           


        
相关标签:
2条回答
  • 2020-12-24 08:51

    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");
    });
    
    0 讨论(0)
  • 2020-12-24 09:12

    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 讨论(0)
提交回复
热议问题