【问题标题】:async await mysql2/promise and ending connection异步等待 mysql2/promise 和结束连接
【发布时间】:2018-05-04 15:29:14
【问题描述】:

尝试使用 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 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();

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

【问题讨论】:

    标签: javascript node.js async-await node-mysql2


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

    2. 创建连接的成本可能很高,并且会影响您的应用程序性能。你应该使用connection pools

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

    【讨论】:

    • 感谢您的回答,但是,如果我们在不同的文件中创建一个池并调用我们的应用程序起点,它将如何为我们提供对该池/连接的引用以使用 pool.getConnection (function(err, connection) { 在应用程序(模型)的其他部分中,我们需要该连接以执行数据库操作??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多