node.js and mysql connection pool does not export

匆匆过客 提交于 2019-12-06 08:33:38

问题


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


回答1:


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();
});



回答2:


The problem you have is your understanding of how callbacks and asychronous calls work in JavaScript and Node.js.

To understand the concept check this article

You will have to change your code to something like this:

db.js

var mySQL = require('mysql');
var pool  = mySQL.createPool({
    host: config.host,
    user: config.user,
    password: config.password,
    database: config.database
});
module.exports.pool = pool.getConnection; // export the pools getConnection

query.js

var dbSql = require('./db');
var userQuery = 'select * from user';
dbSql.pool(function(err, con) { // the function is called when you have a connection
    if(err) throw err; // or handle it differently than throwing it
    console.log("con: " + con); // not undefined anymore
    con.query(userQuery,function(err,user){
        con.release();
    }) 
});


来源:https://stackoverflow.com/questions/35914736/node-js-and-mysql-connection-pool-does-not-export

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!