2017-09-06 152 views
0

我正在使用ExpressJS導入MySQLJS。以ExpressJS作爲後端,我有一個名爲/get-candidates的服務,ExpressJS試圖從MySQL表中獲取一些數據並返回給請求者。
我正在尋找一種在將JSON返回給請求者之前正確關閉MySQL DB連接的方法。ExpressJS - 如何正確關閉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)' 
}; 

回答

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

我不明白你爲什麼要做到這一點,但所有你需要做的就是讓一個變量,並把它連接後的響應。

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

};