NodeJS MySQL - How to know connection is release or not

别说谁变了你拦得住时间么 提交于 2020-02-19 10:01:08

问题


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"


回答1:


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

   });
});



回答2:


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.




回答3:


You can also use below code in every microservice before doing anything.

if(connection.state === 'disconnected'){
    return respond(null, { status: 'fail', message: 'server down'});
}


来源:https://stackoverflow.com/questions/34542902/nodejs-mysql-how-to-know-connection-is-release-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!