Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close database connection in node.js?

When i am closing database connection in node.js i am getting this error

Cannot enqueue Query after invoking quit.

Here is my code

socket.on('adminConnect', function (email) {
    connection = mysql.createConnection(db_config); // db_config has all details of database
    connection.connect(); // no problem in connection
    connection.query("SELECT id FROM user WHERE  email = '" + email + "' ", function (err, results, fields) {
        if (err) throw err;
        if (results[0]) {
            // Some code
            connection.end(); // its giving error "Cannot enqueue Query after invoking quit."
        } else {
            console.log("no id");
        }
    });
});
like image 736
Vardan Avatar asked Oct 24 '13 10:10

Vardan


People also ask

How do I close a node JS connection?

The server. close() method stops the HTTP server from accepting new connections.

How do I close a node connection in mysql?

To close a database connection gracefully, you call the end() method on the connection object. The end() method ensures that all remaining queries are always executed before the database connection closed. To force the connection close immediately, you can use the destroy() method.

Should I close database connection?

Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. To ensure that a connection is closed, you could provide a 'finally' block in your code.


1 Answers

In general, you reuse connections instead of opening/closing all the time.

To answer your question, this is how:

connection.end();

Try putting the line outside the callback, because all the queries must complete before ending a connection, so you're safe like this:

connection.query(.......);
connection.end();

Your code would then be:

socket.on('adminConnect', function (email) {
    connection = mysql.createConnection(db_config); // db_config has all details of database
    connection.connect(); // no problem in connection
    connection.query("SELECT id FROM user WHERE  email = '" + email + "' ", function (err, results, fields) {
        if (err) throw err;
        if (results[0]) {
            // Some code
        } else {
            console.log("no id");
        }
    });
    connection.end();
});
like image 128
randunel Avatar answered Oct 07 '22 15:10

randunel