【问题标题】:MySQL + Express.jsMySQL + Express.js
【发布时间】:2022-02-15 05:02:11
【问题描述】:

我正在构建基于 express.js 的 API 接口,它将接收来自 MySQL 数据库的数据。现在我想知道哪种方法是打开数据库连接的最佳方式。解决方案 A)在 api 服务器启动时打开连接并仅在我关闭 api 服务器时才结束它或 B)在每个请求上打开与 MySQL 的连接并且在接收到数据后结束它?告诉我每种解决方案的优缺点,以及基于类似情况的您自己的解决方案。是的,节点对我来说很新。

【问题讨论】:

    标签: mysql node.js database express


    【解决方案1】:

    使用连接池管理器,因此 1) 您无需为每个请求的打开/关闭连接付出代价 2) 在出现任何错误时,您无需手动管理连接生命周期

    // put this in a code path that runs at startup of your server. No actual connection performed
    const pool  = mysql.createPool({
      connectionLimit : 10,
      host            : 'example.org',
      user            : 'bob',
      password        : 'secret',
      database        : 'my_db'
    });
    
    // put this where you need your db data
    pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
      if (error) throw error;
      console.log('The solution is: ', results[0].solution);
    });
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      • 2018-09-18
      • 2019-07-11
      • 2021-10-29
      • 2018-04-13
      相关资源
      最近更新 更多