5

What is the recommended way to establish database connection and close it properly in Node.js using tedious?

For each and every request we are creating new connection and processing the request then closing them in callback.

app.get('/getData/:id', function(req, res){
    var id = req.params.id;
    var sqlGet = "exec MyStoreProcedure @Id='" + id + "'";
    var connection = new Connection(config);
    var request = new Request(sqlGet, function(err, result){
        connection.close();
        if(err)
            console.log(err);
        else
            res.send(result);
    });

    connection.on('connect', function(err) {
        if (err) 
        {
            console.log(err)
        }else{
            console.log("Connected");
            connection.execSql(request);
        }
    });
});

Is there any other recommended approach to handle this scenario?

Hari Prasath
  • 111
  • 1
  • 2
  • 8

1 Answers1

1

UPDATE (Oct 19, 2020): It appears that tedious-connection-pool is no longer supported/outdated. I've migrated my code to mssql: https://www.npmjs.com/package/mssql

Previous Answer:

You should check out tedious-connection-pool: https://github.com/tediousjs/tedious-connection-pool.

This makes it easy to manage and reuse connections rather than open/close connections continuously.

As part of using connnection pooling, you should extract it out into a separate file so it can be reused across your application.

MattB
  • 1,104
  • 8
  • 15
  • To acquire a connection in router **pool.acquire** is used. Do we need to use pool.acquire for each request when processing or just initializing them once and reusing the connection sent within argument? – Hari Prasath Jun 15 '19 at 10:50
  • connnection pooling seems is out of dated. – Ethan Oct 08 '20 at 05:02
  • Agreed. I've moved away from tedious and implemented mssql (https://www.npmjs.com/package/mssql) – MattB Oct 19 '20 at 15:40
  • mssql package is now out of maintenance as well: https://tediousjs.github.io/tedious/frequently-encountered-problems.html – Rohn Adams Aug 02 '22 at 20:12