【发布时间】: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;
}
上面代码中发生的事情是在连接内部。查询函数有结果,但是一旦我们退出它然后结果是空的,我似乎无法弄清楚原因是什么。
【问题讨论】:
-
您可以使用基于 ORM 的解决方案,例如整理
-
@ZainUlAbidin 你能举个例子吗?
-
sequelize.org/v4/manual/tutorial/querying.html 这会自动处理连接池,并始终为您提供可靠的查询渠道
标签: javascript mysql node.js express promise