NodeJS + mysql - 自动关闭池连接?

NodeJS + mysql - automatically closing pool connections?

我希望通过 NodeJS 与 MySQL 数据库一起使用连接池。根据文档,有两种方法可以做到这一点:要么我明确地从池中获取连接,使用它并释放它:

var pool = require('mysql').createPool(opts);

pool.getConnection(function(err, conn) {
    conn.query('select 1+1', function(err, res) {
        conn.release();
    });
});

或者我可以这样使用:

var mysql = require('mysql');
var pool  = mysql.createPool({opts});

pool.query('select 1+1', function(err, rows, fields) {
  if (err) throw err;

  console.log('The solution is: ', rows[0].solution);
});

如果我使用第二个选项,是否意味着连接会自动从池中拉出、使用和释放?如果是这样,是否有理由使用第一种方法?

以防其他人偶然发现:

当您使用 pool.query 时,您实际上是在调用一个快捷方式,它的作用与第一个示例相同。

来自readme

This is a shortcut for the pool.getConnection() -> connection.query() -> connection.release() code flow. Using pool.getConnection() is useful to share connection state for subsequent queries. This is because two calls to pool.query() may use two different connections and run in parallel.

所以是的,第二个也在调用 connection.release() 你只是不需要输入它。

是的,第二个意味着池负责获取下一个空闲连接,对其进行查询,然后再次释放它。您将其用于 "one shot" 没有依赖关系的查询。

如果您想执行多个相互依赖的查询,请使用第一个。连接保持某些状态,如锁、事务、编码、时区、变量……。

这里是一个改变使用的时区的例子:

pool.getConnection(function(err, conn) {
    function setTimezone() {
       // set the timezone for the this connection
       conn.query("SET time_zone='+02:00'", queryData);
    }

    function queryData() {
       conn.query( /* some query */, queryData);
    }


    function restoreTimezoneToUTC() {
       // restore the timezone to UTC (or what ever you use as default)
       // otherwise this one connection would use +02 for future request
       // if it is reused in a future `getConnection`
       conn.query("SET time_zone='+00:00'", releseQuery);
    }

    function releaseQuery() {
        // return the query back to the pool
        conn.release()
    }

    setTimezone();
});