ExpressJS - How to Properly Close MySQL Connection

I'm using ExpressJS importing MySQLJS. With ExpressJS as back-end, I have a service called /get-candidates where ExpressJS tries to fetch a couple of data from MySQL table and is returned to requester.
I'm looking for a way to properly close MySQL DB Connection before returning the JSON to requester.

Here's what my /get-candidates looks like:

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

Upvotes: 0

Views: 5381

Answers (2)

Satyam Koyani
Satyam Koyani

Reputation: 4274

You can close connection once you get the query results either it is error or successfully fetched records.

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

    });


};

Upvotes: 3

C.Unbay
C.Unbay

Reputation: 2826

I don't see why you want to achieve this, but all you have to do is make a variable and send it a response after connection.

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

};

Upvotes: 1

Related Questions