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");
}
});
});
The server. close() method stops the HTTP server from accepting new connections.
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With