Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS MySQL - How to know connection is release or not

I am developing NodeJS + MySQL web API.

I am using mysql npm module.

I want know connection is release or not is there any function or variable. Like

if(!connection.isRelease() OR !connection.isClose() OR !connection.end()) {
    connection.release();
}

Is there any specific function to know connection is release or not?

I am getting error like "connection already release"

like image 306
Ankur Loriya Avatar asked Dec 31 '15 07:12

Ankur Loriya


People also ask

How do you check is MySQL connected or not?

To check the database connectivity, you must know the database hostname, normally it is “localhost” then database-name, username and password. If the DB is hosted on a remote server [remote DB server], change the host to that server's hostname. Also the connectivity from this machine to DB machine should be enabled.

How do I release a database connection?

You can delete database connections. From the Explore Repository, select Tools, and then Database Connection Manager. In Database Connection Manager, select the database connection to remove, and then click Delete.

How do I close a node JS connection?

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


2 Answers

You can check if the connection is in the pool to see if it was released. The index in the free connections will be -1 if the connection is not released. Here is an example.

var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'localhost',
  user            : 'root',
  password        : ''
});

pool.getConnection(function(err, connection) {
    connection.query( 'SELECT something FROM sometable', function(err, rows) {

      console.log(pool._freeConnections.indexOf(connection)); // -1

      connection.release();

      console.log(pool._freeConnections.indexOf(connection)); // 0

   });
});
like image 140
curtwphillips Avatar answered Sep 24 '22 10:09

curtwphillips


Just in case you don't have access to the pool you can also do this:

connection._pool._freeConnections.indexOf(connection)

This will give you the same answer as the accepted answer.

like image 23
kiwicomb123 Avatar answered Sep 24 '22 10:09

kiwicomb123