Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-mysql connection end or destroy not working

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

like image 577
Cesar Zubillaga Avatar asked May 11 '15 08:05

Cesar Zubillaga


People also ask

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.

How do I close a node JS connection?

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

Can NodeJs communicate with mysql?

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.


1 Answers

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();
});
like image 50
Peter Smartt Avatar answered Oct 28 '22 23:10

Peter Smartt