Use single database connection in entire application?

  • A+

I am creating a application that will communicate over Udp protocol in node js. Also i am using sql server as a database so in order to connect this database i am using mssql npm liabrary. Basically what i am doing i have one separate module for dbcon as shown below

const sql = require('mssql') const config = {     user: 'sa',     password: '123',     server: '', // You can use 'localhost//instance' to connect to named instance     database: 'SBM-EMCURE',      options: {         encrypt: false // Use this if you're on Windows Azure     } }  sql.connect(config, err => {   })  sql.on('error', err => {     console.log('error on sql.on()'); }) module.exports.sql = sql; 

And i am using this exported sql object to run my queries outside dbcon module but it gives me different behavior sometimes like query executes before databse connection, is there is any way to use single database connection for entire application?. Using single database connection is useful or it will slow down my process
Thanks in advance


You could:

  • Pass the instance into each router and use it there when you set them up
  • Set the instance as a property of your app object and access it from or within your middleware functions
  • Set the instance as a property to the global object and access it from anywhere (typically not a best practice)

Also, you're initiating the connection by calling sql.connect(), but you don't give it a callback for when it's finished connecting, and immediately export it and probably query it before the connection is established. Do this:

const util = require('util'); const sql = require('mssql');  const config = {     user: 'sa',     password: '123',     server: '',      database: 'SBM-EMCURE',      options: {         encrypt: false      } };  module.exports = util.promisify(sql.connect)(config)     .then(() => sql) 

Then you can retrieve the instance with:

require('./database.js').then(sql => {     app.sql = sql; }).catch(console.error); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: