ExpressJS - 如何正确关闭MySQL连接

时间:2017-09-06 03:35:04

标签: mysql node.js express promise

我使用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)'
};

2 个答案:

答案 0 :(得分:3)

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

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);
        }

    });


};

答案 1 :(得分:1)

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

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);

};