Cesar Zubillaga
Cesar Zubillaga

Reputation: 61

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

Upvotes: 6

Views: 7986

Answers (2)

Ankur Srivastava
Ankur Srivastava

Reputation: 923

You can use the below code, for cleaner termination .

connection.execute({
      sqlText: 'select * from <TABLENAME>',
      complete: function(err, stmt, rows) {
        if (err) {
          console.error('Failed to execute statement due to the following error: ' + err.message);
        } else {
          numRows =rows.length;
          console.log('Number of rows produced: ' + numRows);
        }
        connection.destroy(function(err, conn) {
          if (err) {
            console.error('Unable to disconnect: ' + err.message);
          } else {
            console.log('Disconnected connection with id: ' + connection.getId());
          }
        });

      }
    });

Upvotes: 0

Peter Smartt
Peter Smartt

Reputation: 358

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();
});

Upvotes: 1

Related Questions