【问题标题】:NodeJS, doesn't close mysql connectionNodeJS,不关闭mysql连接
【发布时间】:2016-02-16 16:39:22
【问题描述】:

我实际上使用了这个MYSQL Client,当我关闭连接时实际上永远不会关闭,所以我可以在状态中看到。

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();
    });

});

【问题讨论】:

    标签: javascript mysql node.js


    【解决方案1】:

    conn.end() 移出查询回调 - 如node-mysql's documentation 中所述:

    您在连接上调用的每个方法都会排队并按顺序执行。

    使用 end() 关闭连接,确保在向 mysql 服务器发送退出数据包之前执行所有剩余的查询。

    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();
    

    【讨论】:

    • 嗨,我试过了,没用,我也试过conn.destroy()的方法,没用。
    • 遇到同样的问题,end() 和 destroy() 不起作用。
    【解决方案2】:

    你也可以使用池。

    检查this link

    可以将连接池化以方便共享单个连接,或者 管理多个连接。

    连接完成后,只需调用 connection.release() 并且连接将返回到池中,准备好再次使用 别人。

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

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多