Mr SC
Mr SC

Reputation: 182

NodeJS, doesn't close mysql connection

I actually use this MYSQL Client and when I close a connection is actually never closes , so I can see in the status.

router.get('/test', function (req, res, next) {

    var conn = mysql.createConnection(config);

    conn.connect();

    conn.query('select  * from invoices ', function (err, result) {

        if (err) {
            throw err;
        }

        res.status(200).json({result: result});
        conn.end();// || conn.destroy();
    });

});

Connections

Upvotes: 2

Views: 3331

Answers (2)

BrTkCa
BrTkCa

Reputation: 4783

Also you can use pool.

Check this link.

Connections can be pooled to ease sharing a single connection, or managing multiple connections.

When you are done with a connection, just call connection.release() and the connection will return to the pool, ready to be used again by someone else.

pool.end(function (err) {
  // all connections in the pool have ended
});

Upvotes: 0

baao
baao

Reputation: 73211

Move conn.end() out of the query callback - as described in node-mysql's documentation:

Every method you invoke on a connection is queued and executed in sequence.

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  if (err) throw err;

  console.log('The solution is: ', rows[0].solution);
});

connection.end();

Upvotes: 4

Related Questions