【问题标题】:Close connection MySQL Node.js关闭连接 MySQL Node.js
【发布时间】:2015-09-18 11:13:16
【问题描述】:

我正在使用 ExpressJS 和 MySQL 开发一个 Node 应用程序。我正在使用这个模块https://github.com/felixge/node-mysql/,我还在学习它的使用。 我在如何正确关闭连接方面遇到了麻烦。

这就是我的工作:

app.post('/example', function (req, res) {

    //BD
    var connection = mysql.createConnection({
        host: config.database.host,
        port: config.database.port,
        user: config.database.user,
        password: config.database.password,
        database: config.database.database
    });

    var sql = '';

    if (varExample != null) {

         sql = 'Random query';

         connection.query(sql, function (err, results) {

             //Get results

             connection.end();
         }); 
    }
});

有时我必须多次调用此方法才能在数据库中插入数据。那时我收到一个错误“连接太多”。

在这些情况下关闭连接的方法是什么?

【问题讨论】:

    标签: node.js node-mysql


    【解决方案1】:

    我意识到已经有一个公认的答案,但您真正应该做的是创建一个数据库池,其他答案确实没有给出示例。您必须将其设置为与创建与库的普通数据库连接稍有不同。

    -edit 你不必担心关闭连接。

        var mysql = require('mysql');
        var pool  = mysql.createPool({
          connectionLimit : 10,
          host            : 'example.org',
          user            : 'bob',
          password        : 'secret'
        });
    
        pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
          if (err) throw err;
    
          console.log('The solution is: ', rows[0].solution);
        });
    
    exports.Pool = pool;
    

    【讨论】:

    • 不关闭的问题是,如果从批处理运行,节点永远不会退出。那么我们如何才能有秩序地终止呢?
    【解决方案2】:

    你不应该做的是每次收到请求时都打开一个连接。每次连接都很慢,其次驱动程序通常会为您打开一个连接池,所以应该不是问题。无需关闭与mysql的连接。

    基本上你必须这样做

    //BD
    var connection = mysql.createConnection({
        host: config.database.host,
        port: config.database.port,
        user: config.database.user,
        password: config.database.password,
        database: config.database.database
    });
    app.post('/example', function (req, res) {
        var sql = '';
    
        if (varExample != null) {
    
             sql = 'Random query';
    
             connection.query(sql, function (err, results) {
    
                //Get results
             });  
        }
    });
    

    编辑:添加池选项 拥有一个连接池基本上是我们大多数人想要的服务器必须执行许多查询。 它只是稍微改变了您创建连接的方式。

    var connection  = mysql.createPool({
      connectionLimit : 10,
      host            : 'example.org',
      user            : 'bob',
      password        : 'secret'
    });
    

    【讨论】:

    • 这个解决方案有问题。在这种情况下,我重复使用相同的连接来进行不同的查询节点回答“调用退出后无法将查询排队”
    • S抱歉,您必须删除 connection.end()
    • 也许这是一个愚蠢的问题,但是,Node 如何在请求后设法关闭连接?
    • 为什么一定要关闭连接?驱动程序创建了一个连接池,它们很容易被使用……当你不再需要使用它时,你关闭了连接。但是作为一个节点服务器,我猜它会运行很长时间,而且我猜你会更多次使用 mysql,你只需保持它打开
    • @DevAlien 默认情况下,驱动程序不会创建连接池。看看我创建数据库池的答案。设置与您在此处的设置略有不同。
    猜你喜欢
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 2016-04-04
    • 2012-10-12
    • 2020-02-07
    • 2014-12-18
    • 2012-11-03
    • 1970-01-01
    相关资源
    最近更新 更多