How do I create a MySQL connection pool while working with NodeJS and Express?

Utkarsh Kaushik picture Utkarsh Kaushik · May 8, 2016 · Viewed 35.4k times · Source

I am able to create a MySQL connection like this:

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'me',
    password : 'secret',
    database : 'my_db'
});

connection.connect();

But I would rather like to initiate a pool and use it across my project.

Answer

Utkarsh Kaushik picture Utkarsh Kaushik · May 8, 2016

Just to help some one in future, this worked for me:

I created a mysql connector file containing the pool:

// Load module
var mysql = require('mysql');
// Initialize pool
var pool      =    mysql.createPool({
    connectionLimit : 10,
    host     : '127.0.0.1',
    user     : 'root',
    password : 'root',
    database : 'db_name',
    debug    :  false
});    
module.exports = pool;

Later you can simply include the connector in another file lets call it manageDB.js:

var pool = require('./mysqlConnector');

And made a callable method like this:

exports.executeQuery=function(query,callback){
    pool.getConnection(function(err,connection){
        if (err) {
          connection.release();
          throw err;
        }   
        connection.query(query,function(err,rows){
            connection.release();
            if(!err) {
                callback(null, {rows: rows});
            }           
        });
        connection.on('error', function(err) {      
              throw err;
              return;     
        });
    });
}