如何捕获数据库连接状态或ping连接?

时间:2014-12-26 14:23:05

标签: javascript mysql node.js express

对Node.js使用MySql driver,这是我的ping方法:

function ping(){
  connection.connect(function(err) {
    if (err) {
      console.error('error connecting: ' + err.stack);
      return false;
    }

    console.log('connection authenticated: ' + (connection.state == "authenticated"));
    console.log('connected as id ' + connection.threadId);
  });

  console.log("connection: " + connection.state);
  return (connection.state == "authenticated");
}

显然,这个node-mysql库没有本机Ping方法。我认为这将有利于它。但是,我在控制台中看到以下问题:

  

调试器侦听端口53213
  连接:断开连接   12月26日星期五   2014 14:12:38 GMT RazorJS Express服务器监听端口3000
  连接验证:真实   连接为id 17

在连接实际打开之前,似乎正在记录连接状态并返回false。也许这是在执行异步?如何让它同步运行?

1 个答案:

答案 0 :(得分:0)

你在connection.connect函数的回调之外编写了以下内容。所以在你的connection.connect执行它的回调之前,下面的代码被执行(node.js的异步性质),因此它的第一个被安排为断开连接。

console.log("connection: " + connection.state);
  return (connection.state == "authenticated");

以上内容应该在回调中。

    function ping() {
    connection.connect(function(err) {
        if (err) {
            console.error('error connecting: ' + err.stack);
            return false;
        }
        console.log('connection authenticated: ' + (connection.state == "authenticated"));
        console.log('connected as id ' + connection.threadId);
        console.log("connection: " + connection.state);
        return (connection.state == "authenticated");
    });
}