Search code examples
mysqlnode.jsnode-mysql

node.js and mysql connection pool does not export


I am unable to export a pool connection in node.js. What I want is to get the connection from the pool from the db.js and use it and then release it after using it.

db.js

var mySQL = require('mysql');
    var pool  = mySQL.createPool({
        host: config.host,
        user: config.user,
        password: config.password,
        database: config.database
    });
    var getConnection = function() {
        pool.getConnection(function(err, connection) {
            if(err) throw err;
            return connection;
        });
    };
    module.exports.pool = getConnection;

query.js

var dbSql = require('./db');
var userQuery = 'select * from user';
var con = dbSql.pool();
console.log("con: " + con); //displays undefined
con.query(userQuery,function(err,user){
   con.release();
})

above when I do console.log("con: " + con); it displays undefined


Solution

  • You are exporting a function, not the pool itself. Besides, getConnection is not accepting any callback:

    db.js should be something like this:

    var mySQL = require('mysql');
    var pool  = mySQL.createPool({
        host: config.host,
        user: config.user,
        password: config.password,
        database: config.database
    });
    var getConnection = function (cb) {
        pool.getConnection(function (err, connection) {
            //if(err) throw err;
            //pass the error to the cb instead of throwing it
            if(err) {
              return cb(err);
            }
            cb(null, connection);
        });
    };
    module.exports = getConnection;
    

    query.js should be something like this:

    var getConnection = require('./db');
    getConnection(function (err, con) {
      if(err) { /* handle your error here */ }
      var userQuery = 'select * from user';
      console.log("con: " + con); //displays undefined
      con.query(userQuery,function(err,user){
      con.release();
    });