I don't know why mysql.end() or mysql.destroy() are not working as i expect. This is my code.
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'db',
password: ''
});
connection.connect();
connection.query('SELECT * FROM ofertas ', function (err, rows, fields)
{
if (err) console.log(err);
else
{
console.log(rows);
}
});
connection.destroy(function (err)
{
if (err) throw err;
});
I execute this code and then i go to mysql command line and i type this :
show status like 'Conn%';
Before node code
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 3 |
+---------------+-------+
After node code
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 4 |
+---------------+-------+
connection.state = 'disconnected'
Thanks
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.
The server. close() method stops the HTTP server from accepting new connections.
Here we are calling connect function on the connection variable which we have created already. Now we will see the following output on the terminal as shown in the screenshot: In this way, NodeJs application can be connected with the Mysql database.
You need to wait until the query is finished before you can destroy the connection. Try
connection.query('SELECT * FROM ofertas ', function (err, rows, fields)
{
if (err) console.log(err);
else
{
console.log(rows);
}
connection.destroy();
});
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