javascript - 异步等待 mysql2/promise 和结束连接
问题描述
尝试使用 MySQL 数据库在 Node.Js 中开发 REST API。你能帮我写一些更好的代码吗?
这里有两个最重要的问题,
1 - How we can take the createConnection logic out of userModel.js?
2 - Shall I end the connection on every API call?
预测答案
filename : db.js
const mysql = require('mysql2/promise');
module.exports = async function(){
return await mysql.createConnection({host:'localhost', user: 'user', password:'pass', database: 'database'});
}
and in userModel.js
const mysql = require('db.js');
module.exports.getProfile(user_id){
try{
const [rows, fields] = await db.execute('SELECT * FROM `table` WHERE `user_id` = ?', [1]);
console.log(rows);
}catch(err){
console.log(err);
}
await db.end();
}
如果我们尝试再次使用 “{ Error: Can't add new command when connection is in close state at PromiseConnection.execute”尝试再次访问 API,上述代码实现将产生错误
也许如果使用这种看起来很愚蠢的下面给出的方法,我们可以再次调用相同的 API n 而不会出现任何错误。
userModel.js 中还有很多函数,在这种情况下,我们必须创建并结束与每个 API 方法的连接。
userModel.js
const mysql = require('mysql2/promise');
const db = await mysql.createConnection({host:'localhost', user: 'user', password:'pass', database: 'database'});
try{
const [rows, fields] = await db.execute('SELECT * FROM `table` WHERE `user_id` = ?', [1]);
console.log(rows);
}catch(err){
console.log(err);
}
await db.end();
任何建议都会有所帮助。问候,
解决方案
连接可以在您的服务器启动时完成。您应该将此代码放在启动服务器的文件中。
创建连接可能会很昂贵,并且会影响您的应用程序性能。您应该使用连接池
稍有不同的是,硬编码参数以连接到数据库并不是一个好主意。您应该保留一个配置文件,可以根据环境从中读取这些值。
推荐阅读
- python - 在为基于 verse 主题的古兰经经文检索系统构建我的 doc2vec 嵌入模型时需要帮助
- python - 库记录器应该只有空处理程序吗?
- swift4.2 - 如何在 Swift 4.2 中使用 SDWebImage 使用 headerView 完成块?
- python - 我用 pyinstaller 创建的 exe 闪烁并终止
- c - C-结构函数
- python-3.x - Opencv中使用multiTracker对象的多对象跟踪初始化
- java - java编译器如何以及在哪里存储.class文件
- java - 如何找到ascii数组的总和?
- c++ - 删除后的c ++指针仍然占用内存
- wix - 取消安装 Wix Burn Boostrapper 并删除 ARP 条目