Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database connection using tedious

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?

like image 859
Hari Prasath Avatar asked Nov 07 '22 16:11

Hari Prasath


1 Answers

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.

like image 62
MattB Avatar answered Nov 16 '22 09:11

MattB