【问题标题】:MySQL Can not open connection after call connection.end() => Error: Pool is closedMySQL 调用 connection.end() => 后无法打开连接 => 错误:池已关闭
【发布时间】:2022-01-10 21:49:57
【问题描述】:

config.js

const mysql = require('mysql2');

const config = {
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: 'root',
    database: 'krometal',
    charset: "utf8mb4_bin",
    multipleStatements: true
};
const connection = mysql.createPool(config);

connection.getConnection(function (err, connection) {
    //connecting to database
    if (err) {
        logger.log('error', err);
        console.log("MYSQL CONNECT ERROR: " + err);
    } else {
        logger.log('info', "MYSQL CONNECTED SUCCESSFULLY.");
        console.log("MYSQL CONNECTED SUCCESSFULLY.");
    }
});

module.exports = {
    connection
}

login.js

const loginUser = async (req, callback) => {
  connection.query(sql, async function (err, rows) => {
      // logic
      callback(result, 401, connection);
  })
}

route.js

users.post('/users/login', async (req, res) => {
    await loginUser(req, async (response, code, connection) => {
        await connection.end();
        res.status(code).send(response);
    });
});

问题是我第一次尝试登录时工作正常,但如果我再次尝试相同的登录 API,则会抛出错误 Error: Pool is closed.

我应该使用

connection.end()

方法是每次打开连接还是mysql2自动结束连接?

【问题讨论】:

    标签: javascript mysql node.js database node-mysql2


    【解决方案1】:

    别跑

    await connection.end();
    

    运行此功能后,您需要使用创建新连接

    connection.getConnection();
    

    【讨论】:

    • 我删除了await connection.end();,一切正常,但在大范围内,连接将达到极限。
    • 我应该把connection.getConnection();放在哪里,为什么?我认为一旦我点击任何 api 就应该打开连接
    • @HusseinMohamed 我认为每次收到请求时打开新连接并不是一个好主意。性能将是一个大问题。
    • @HusseinMohamed 文档说,您可以在不使用 pool.getConnection() 的情况下使用 pool.queryhttps://github.com/mysqljs/mysql#pooling-connections
    猜你喜欢
    • 2021-01-05
    • 2013-02-05
    • 2018-04-03
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2011-11-14
    相关资源
    最近更新 更多