【问题标题】:ExpressJS - How to Properly Close MySQL ConnectionExpressJS - 如何正确关闭 MySQL 连接
【发布时间】:2018-02-14 10:08:40
【问题描述】:

我正在使用ExpressJS 导入MySQLJS。使用 ExpressJS 作为后端,我有一个名为 /get-candidates 的服务,ExpressJS 尝试从 MySQL 表中获取一些数据并返回给请求者。
我正在寻找一种在将 JSON 返回给请求者之前正确关闭 MySQL 数据库连接的方法。

这是我的/get-candidates 的样子:

module.exports.getCandidates = function (request, response) {

    var mysql = require("mysql");
    var connectionSettings = require("../db.conf.json");
    var connection = mysql.createConnection(connectionSettings);

    connection.connect();

    connection.query('SELECT * FROM Candidates', function (err, rows, fields) {
        if (err) {
            throw err;
        } else {
            response.json(rows);
        }
    });

    connection.end(); // I don't think the code reaches this part after line 'response.json(rows)'
};

【问题讨论】:

    标签: mysql node.js express promise


    【解决方案1】:

    您可以在获得查询结果后关闭连接,无论是错误还是成功获取记录。

    module.exports.getCandidates = function(request, response) {
    
        var mysql = require("mysql");
        var connectionSettings = require("../db.conf.json");
        var connection = mysql.createConnection(connectionSettings);
    
        connection.connect();
    
        connection.query('SELECT * FROM Candidates', function(err, rows, fields) {
    
            connection.end();
    
            if (err) {
                throw err;
            } else {
                response.json(rows);
            }
    
        });
    
    
    };
    

    【讨论】:

      【解决方案2】:

      我不明白您为什么要实现这一点,但您所要做的就是创建一个变量并在连接后向其发送响应。

      module.exports.getCandidates = function (request, response) {
      
      var mysql = require("mysql");
      var connectionSettings = require("../db.conf.json");
      var connection = mysql.createConnection(connectionSettings);
      var myRows; // our variable
      
      connection.connect();
      
      connection.query('SELECT * FROM Candidates', function (err, rows, fields) {
          if (err) {
              throw err;
          } else {
              myRows = rows;
              //response.json(rows);
          }
      });
      
      connection.end(); 
      
      console.log(myRows); // To check if we have the value
      response.json(myRows);
      
      };
      

      【讨论】:

        猜你喜欢
        • 2018-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 2023-03-22
        • 1970-01-01
        相关资源
        最近更新 更多