【问题标题】:nodejs + mysql: how can i reopen mysql after end()?nodejs + mysql:如何在 end() 之后重新打开 mysql?
【发布时间】:2014-09-24 04:26:11
【问题描述】:

代码如下:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host      : 'localhost',
  port      :"3306",
  database  :"mydb",
  user      : 'root',
  password  : '007007',
});
var isCon = true;
connection.connect(
    function  (err) {
        console.log(isCon);
        if (err) {
           isCon=false;
           console.error("error connecting :"+err);
           return;
       };
   }
   );
if(isCon){
    connection.query('select * from tb_items', function(err, result) {
        if (err) throw err;
        console.log('The solution is: ', result);
        console.log('The typeof solution is ',typeof(result));
        debugger;
    });
    connection.end();
}

connection.connect(
    function  (err) {
        console.log(isCon);
        if (err) {
           isCon=false;
           console.error("error connecting :"+err);
           return;
       };
   }
   );
if(isCon){
    connection.query('select * from tb_items', function(err, result) {
        if (err) throw err;
        console.log('The solution is: ', result);
        console.log('The typeof solution is ',typeof(result));
        debugger;
    });
    connection.end();
}

我刚刚打开()-->连接()-->查询()-->结束(),然后又做了一次,但是第二次出现错误:错误:调用退出后无法排队握手. 问题:也许我不能在 end() 之后重新打开它。但我只是想知道,如果我 end(),我该如何重新打开它?

【问题讨论】:

    标签: mysql node.js


    【解决方案1】:

    不,您不能,只需创建另一个。连接类中的所有状态仅与当前连接相关,因此可以使用“reopenWithSameConfig”方法,但您应该从外部执行此操作。

    此外,您无需关闭每个查询的连接 - 只需继续重复使用它而不调用 .end()

    如果你想要多个连接并自动处理死连接,你应该使用 Pool 类。

    还有一点需要注意:您的 isCon 检查不正确,connection.queryconnect() 回调之前被调用,所以它总是正确的。只检查query 回调本身的错误是安全的。如果连接不成功,则会将错误传播到排队的命令

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-13
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2021-05-03
      • 2016-03-24
      相关资源
      最近更新 更多