TIMEX
TIMEX

Reputation: 271584

How do I use the same MySQL connection(s) for my entire Node.js app?

I have an app.js. I run my entire app from there.

Inside app.js, I require many files that have code in it.

For each of these files, I do this:

var mysql = require('mysql');
var mclient = mysql.createConnection({
    host: settings.MYSQL.HOST,
    user: settings.MYSQL.USER,
    password: settings.MYSQL.PASSWORD,
    database: settings.MYSQL.DB,
});

Essentially, I am initiating a new connection for every file.

I want my app.js to make ONE connection, and then pass it to every file during the require line. How can I pass the connection to them so those files can use it?

(Or how can I pass a pool of connections to them?)

Upvotes: 8

Views: 5849

Answers (2)

Kaushik Chatterjee
Kaushik Chatterjee

Reputation: 11

Yes you can use the mclient to attach your query

var mysqlLib = require("mysqlLib");

mysqlLib.getConnection(function(err, mclient) {
  //do queries that you need
  var sql = '//Your SQL here';
  var inserts = [your inserts here];
  sql = mysql.format(sql, inserts);
  mclient.query(sql, function (err, rows) {

  if (err) {
                //handle error here
            }

  })
});

Upvotes: 1

go-oleg
go-oleg

Reputation: 19480

You can create a separate module, call it mysqlLib.js that will be responsible for creating a pool and returning connections:

var mysql = require("mysql");
var pool = mysql.createPool(/* credentials go here */);

exports.getConnection = function(callback) {
  pool.getConnection(function(err, conn) {
    if(err) {
      return callback(err);
    }
    callback(err, conn);
  });
};

and in any module/file that needs a mysql connection, you can do this:

var mysqlLib = require("mysqlLib");

mysqlLib.getConnection(function(err, mclient) {
  //do queries that you need
});

The way require() works, the code in mysqlLib.js will only be run once so only one pool will be created even if require("mysqlLib.js"} is called in multiple files. See this section of the node.js docs for an explanation of module cacheing.

Upvotes: 13

Related Questions