尝试使用 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();
任何建议都会有所帮助。问候,