首页 > 解决方案 > 异步等待 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();

任何建议都会有所帮助。问候,

标签: javascriptnode.jsasync-awaitnode-mysql2

解决方案


  1. 连接可以在您的服务器启动时完成。您应该将此代码放在启动服务器的文件中。

  2. 创建连接可能会很昂贵,并且会影响您的应用程序性能。您应该使用连接池

稍有不同的是,硬编码参数以连接到数据库并不是一个好主意。您应该保留一个配置文件,可以根据环境从中读取这些值。


推荐阅读