0

我正在使用 mysql(8.x) 开发 nodejs。我已经从 npm安装了mysql 库。

我写了一些如下代码。

档案 A -connection.js

const pooledConInfo = { 
    host: 'localhost',
    user: 'user',
    password: 'pw',
    database: 'db',
    insecureAuth : true,
    connectionLimit : 10, 
};
const pooledConnection = mysql.createPool(pooledConInfo);
module.exports = pooledConnection;

文件 B -MemberRouter.js

const con = require('../db/connection');

...

router.get('/api/member', (req, res, nxt) => {
    let rs = Object.assign({}, resForm);
    try {
        con.getConnection((err, connection) => { // #1. Do not want to repeat in every query situation
            if(err) throw err;
            connection.query('SELECT * FROM MEMBER LIMIT ?', 10, (err, result, fields) => {
                connection.release(); // #2. Do not want to repeat in every query situation
                if(err) throw err;
                rs.data = result;
                return res.json(rs);
            })
        });
    } catch (queryException) {
        rs.cause = queryException;
        return res.json(rs);
    }
});

它有效,但我不相信人们会这样使用。

这是我想问的主要两个问题

  • 最烦人的部分是我必须在每个查询回调中释放每个池。是不是正确的方式
  • 有什么好的模式可以应用吗?我想包装getConnectionconnection.release分开...

谢谢

4

1 回答 1

0

您不需要每次都为池连接执行 connect.release() 并且它会自动完成

根据文档

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

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

这是 pool.getConnection() -> connection.query() -> connection.release() 代码流的快捷方式。使用 pool.getConnection() 对于为后续查询共享连接状态很有用。这是因为对 pool.query() 的两次调用可能使用两个不同的连接并并行运行。这是基本结构:

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

pool.getConnection(function(err, connection) {
  if (err) throw err; // not connected!

  // Use the connection
  connection.query('SELECT something FROM sometable', function (error, results, fields) {
    // When done with the connection, release it.
    connection.release();

    // Handle error after the release.
    if (error) throw error;

    // Don't use the connection here, it has been returned to the pool.
  });
});

图片来自你分享的官网

于 2020-01-29T12:58:07.753 回答