【问题标题】:How to properly create mysql2 connection with error handling in a separate file如何在单独的文件中正确创建带有错误处理的 mysql2 连接
【发布时间】:2021-06-08 20:12:43
【问题描述】:

我正在尝试使用 node.js 和 mysql2 实现以下连接方法,但是缺少某些内容并且我遇到了各种错误(主要是 db.query is not a function)。

键如下:

  • 重用已创建的连接
  • 错误处理
  • 连接失败时自动重新连接

原创(查看下方更新):

//dbConnection.js

const mysql = require('mysql2/promise');
const dbConfig = {
    host: 'localhost',
    user: 'user',
    database: 'db',
    password: 'pass'
};

var connection;

//Exporting to use it elsewhere
module.exports = async function connect() { 
    if (connection){
        //so if the connection is already exists use it again
        return connection;
    }
    try {
        connection = await mysql.createConnection(dbConfig);    
        console.info("Connected to MySql on '" + db_config.host + "'");
        return connection;
    } catch (error) {
        console.error('Error when connecting to MySql:', error);
        // auto retry in 5 seconds
        setTimeout(connect, 5000);
    }
}
//dbRoutes.js

const db = require('./dbConnection.js');

dbRouter.get('/get_user', async (req, res, /* next */) => {
    const userId = req.userId;
    await db.query(
        `SELECT * FROM users WHERE id = ${userId};`,
        (err, result) => {
            return res.status(200).send({
                msg: 'success',
                user: result
            });
        }
    );
});

更新:

我能够让它工作,但我不确定这是最好的方法,所以我要求你想到任何改进。

//dbConnection.js

const mysql = require('mysql2/promise');

const db_config = {
    host: 'localhost',
    user: 'root',
    database: 'bln',
    password: ''
};

var connection;
const connect = async function () { 
    if (connection){
        return connection;
    }

    try {
        connection = await mysql.createConnection(db_config);
        console.info("Connected to MySql on '" + db_config.host + "'");
        return connection;
    } catch (error) {
        console.error('Error when connecting to db:', error);
        connection = undefined;
        setTimeout(connect, 5000);
    }
}

module.exports = connect;

//dbRoutes.js

const dbc = require('./dbConnection.js');

dbRouter.post('/login', userMiddleware.validateLogin, async (req, res) => {
    const db = await dbc();
    const [results] = await db.execute(`SELECT * FROM users WHERE email = ?;`, [req.body.email]);
  return res.status(401).send({
        msg: 'success',
    user: result
    });
});

【问题讨论】:

  • module.exports = async ... 表示您返回一个承诺,这意味着const db = require... 将是一个承诺对象,而不是已解决的承诺。
  • 谢谢,我也删除了等待,但不幸的是这不是主要问题。
  • 我同意。这里的主要问题是我认为对异步代码在 JS 中的工作方式存在误解。您不能只删除 async 关键字。你上面代码的前提是错误的。
  • 我理解它只是还没有信心使用它。

标签: node.js mysql2


【解决方案1】:

正如之前的帖子中所说,我们得到的是一个 Promise 对象,而不是连接本身。因此,只需使用辅助文件中的 .then() 方法获取 promise 的解析值。

const connectPromise = require('./dbConnection.js');
let db;
connectPromise.then(c => {
  db = c;
});

现在我们可以使用 db.query

【讨论】:

  • 这里的错误处理在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2021-08-29
  • 1970-01-01
  • 2014-12-10
相关资源
最近更新 更多