1

While trying to connect SQL DB from a NodeJs class, I am getting an error:

ConnectionError: Connection not yet open

var sql = require("mssql");
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
var executeQuery = function(res, query) { 

var conn = new sql.ConnectionPool(dbConfig);

conn.connect()
     .then(function (pool) {

         // create Request object
         var request = new sql.Request(pool);                          
         // query to the database
         request.query(query, function (err, queryResult) {
             if (err) {
                 console.log(err);
                 res.send(err);
             } else {
                 res.send(queryResult);
             }
         });
         conn.close();
    });           
}

1 Answer 1

1

You're closing the connection before request.query is processed as this is an async call. Move conn.close() inside the callback for request.query.

var conn = new sql.ConnectionPool(dbConfig);

conn.connect()
     .then(function (pool) {

         // create Request object
         var request = new sql.Request(pool);                          
         // query to the database
         request.query(query, function (err, queryResult) {
             if (err) {
                 console.log(err);
                 res.send(err);
             } else {
                 res.send(queryResult);
             }
             conn.close();
         });
    });           
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.