Utkarsh Kaushik Utkarsh Kaushik - 1 year ago 54
MySQL Question

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

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'


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

Answer Source

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     : '',
    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:

        if (err) {
          throw err;
            if(!err) {
                callback(null, {rows: rows});
        connection.on('error', function(err) {      
              throw err;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download