Saturday 18 March 2017

node.js mssql javascript method second time call to fetch data from database prints undefined.

I have issues with the following code using the mssql module of nodejs:

A) Function getAllRecords_B prints "undefined" on second call to it. (As can be seen in the code, what I am trying to do is : I want to pass the connection object to it so that it can pick one connection from the pool and use it instead of creating connections again and again.)

B) THe second time function call of getAllRecords_C says the connection has been closed already. How to overcome this problem?

    var fs = require("fs");
    var sql = require("mssql");
    var config = {  
        "server": "localhost",
        "user": "xxx",
        "password": "xxx",
        "database": "TestAutomation",
         "port": 1433 
    };

    getAllRecords_B = function (conn, quer, callback) {
        conn.connect(function (err){
            var request = new sql.Request(conn); // or: var request = connection1.request(); 
            request.query(quer, function(err, recordset) {
                //console.dir(recordset);
                conn.close();
                callback(recordset);
            });
        });
}

function getAllRecords_C(configuration) {
  return sql.connect(configuration).then(function() {
      var retVal = new sql.Request().query('select * from USERSTATUS');
    }).catch(function(err) {
        console.log("Error1", err);
    }).catch(function(err) {
    console.log("Error2", err);
  });
}

console.log("---------------------------------");
var connection = new sql.Connection(config);

var query1 = "select * from USERSTATUS";
getAllRecords_B(connection, query1, function(recs) {
    console.log(recs);
});

getAllRecords_B(connection, query1, function(recs) {
    console.log(recs);
});



via win

No comments:

Post a Comment