Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js Global connection already exists. Call sql.close() first

I'm trying to create web services using node.js from an sql server database,in the frontend when i call those 2 webservices simultaneously it throws an error Global connection already exists. Call sql.close() first .

Any Solution ?

var express = require('express');
var router = express.Router();
var sql = require("mssql");

router.get('/Plant/:server/:user/:password/:database', function(req, res, next) {

    user = req.params.user;
    password = req.params.password;
    server = req.params.server;
    database = req.params.database;


    // config for your database
    var config = {
        user: user,
        password: password,
        server: server,
        database:database

    };

    sql.connect(config, function (err) {



        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query("SELECT  distinct PlantName FROM MachineryStateTable"
            , function (err, recordset) {

                if (err) console.log(err)
                else {

                    for(i=0;i<recordset.recordsets.length;i++) {
                        res.send(recordset.recordsets[i])
                    }

                }
               sql.close();

            });

    });

});





router.get('/Dep/:server/:user/:password/:database/:plantname', function(req, res, next) {

    user = req.params.user;
    password = req.params.password;
    server = req.params.server;
    database = req.params.database;
    plantname = req.params.plantname;

    // config for your database
    var config = {
        user: user,
        password: password,
        server: server,
        database:database

    };

    sql.connect(config, function (err) {



        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query("SELECT  distinct DepName FROM MachineryStateTable where PlantName= '"+plantname+"'"
            , function (err, recordset) {

                if (err) console.log(err)
                else {

                    for(i=0;i<recordset.recordsets.length;i++) {
                        res.send(recordset.recordsets[i])

                    }
                    sql.close();
                }

            });
    });
});



module.exports = router;
like image 235
Laamiri Oussema Avatar asked Jun 25 '17 09:06

Laamiri Oussema


3 Answers

You have to create a poolConnection try this:

new sql.ConnectionPool(config).connect().then(pool => {

  return pool.request().query("SELECT * FROM MyTable")

  }).then(result => {

    let rows = result.recordset
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.status(200).json(rows);
    sql.close();

  }).catch(err => {

    res.status(500).send({ message: `${err}`})
    sql.close();

  });
like image 74
bams Avatar answered Nov 03 '22 07:11

bams


From the documentation, close method should be used on the connection, and not on the required module,

So should be used like

var connection = new sql.Connection({
user: '...',
password: '...',
server: 'localhost',
database: '...'
});
connection.close().

Also couple of suggestions,
1. putting res.send in a loop isn't a good idea, You could reply back the entire recordsets or do operations over it, store the resultant in a variable and send that back.
2. Try using promises, instead of callbacks, it would make the flow neater

like image 30
Shivam Avatar answered Nov 03 '22 07:11

Shivam


You must use ConnectionPool.

Next function returns a recordset with my query results.

async function execute2(query) {

    return new Promise((resolve, reject) => {

        new sql.ConnectionPool(dbConfig).connect().then(pool => {
            return pool.request().query(query)
        }).then(result => {

            resolve(result.recordset);

            sql.close();
        }).catch(err => {

            reject(err)
            sql.close();
        });
    });


}

Works fine in my code!

like image 2
ehitel rodriguez castro Avatar answered Nov 03 '22 05:11

ehitel rodriguez castro