【问题标题】:Querying a Mysql connection in nodejs using connectionPool使用connectionPool在nodejs中查询Mysql连接
【发布时间】:2021-11-22 07:57:31
【问题描述】:

我正在使用 Nodejs、express 和 MySQL 制作网站。

我面临的问题是,我现在与数据库建立连接和查询的方式始终是连接的,因此最终会超时。我尝试使用 Pools,但我遇到了一个问题,当我希望通过函数调用连接然后返回查询结果时,我不需要每次想要查询特定的代码时都重复相同的代码查询。

这是我现在创建连接的方式,然后每当调用函数时,它都会查询代码并返回查询结果。

const mysql = require('promise-mysql');

let db;

(async function (err)
{
    db = await mysql.createConnection({
        host: dotenv.parsed.DB_HOST,
        user: dotenv.parsed.DB_LOGIN,
        password: dotenv.parsed.DB_PASSWORD,
        database: dotenv.parsed.DB_NAME,
        charset: dotenv.parsed.DB_CHAR,
        multipleStatements: dotenv.parsed.DB_MULTI
    });
    if (err){console.log(err);};
    process.on('exit', () => {db.end()});
})();

/**
* @description gets the user's personnumber and password
* @param {*} personnummer is the personal number issued by the Swedish government for the person in question 
*/
async function getPat(personnummer)
{
    let sql = "SELECT * FROM patients where personnummer=?";
    let res = await db.query(sql, [personnummer]);
    return res;
}

那么我将如何在池中进行此操作?因为当我尝试在游泳池中这样做时

const connection = mysql.createPool({
    host: dotenv.parsed.DB_HOST,
    user: dotenv.parsed.DB_LOGIN,
    password: dotenv.parsed.DB_PASSWORD,
    database: dotenv.parsed.DB_NAME,
    charset: dotenv.parsed.DB_CHAR,
    multipleStatements: dotenv.parsed.DB_MULTI
});

/**
* @description gets the user's personnumber and password
* @param {*} personnummer is the personal number issued by the Swedish government for the person in question 
*/
async function getPat(personnummer)
{
    let patient;
    (await connection).getConnection(function (err, connection)
    {
        if (err) throw err;
        connection.query("SELECT * FROM patient where personnummer=?", [personnummer], function (err, result)
        {
            if (err) throw err;
            patient = result;
        });
    });

    return patient;
}

上面代码中发生的事情是在连接内部。查询函数有结果,但是一旦我们退出它然后结果是空的,我似乎无法弄清楚原因是什么。

【问题讨论】:

标签: javascript mysql node.js express promise


【解决方案1】:

根据the documentationmysql.createPool()会同步返回一个pool,因此不需要等待。

// mysql.createPool() returns a pool synchronously
const pool = mysql.createPool({
    'host': dotenv.parsed.DB_HOST,
    'user': dotenv.parsed.DB_LOGIN,
    'password': dotenv.parsed.DB_PASSWORD,
    'database': dotenv.parsed.DB_NAME,
    'charset': dotenv.parsed.DB_CHAR,
    'multipleStatements': dotenv.parsed.DB_MULTI
});

文档没有告诉您如何承诺 pool.query(),而这正是您所缺少的。

有一些实用程序可以满足您的需求,但手动操作非常简单。

/**
* @description returns a Promise that delivers the user's personnumber and password (or Error)
* @param {*} personnummer is the personal number issued by the Swedish government for the person in question 
*/
async function getPat(personnummer) {
    return new Promise((resolve, reject) => {
        pool.query("SELECT * FROM patient where personnummer=?", [personnummer], function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
}

由于 getPat() 返回 Promise,其调用者必须使用 .then() 语法或 await 语法才能访问结果。

【讨论】:

    猜你喜欢
    • 2014-07-17
    • 2015-11-01
    • 2010-12-05
    • 2022-01-02
    • 1970-01-01
    • 2021-05-10
    • 2010-12-28
    • 2011-07-20
    • 2015-10-12
    相关资源
    最近更新 更多