node.js 和 mysql 连接池不导出

node.js and mysql connection pool does not export

我无法在 node.js 中导出池连接。我想要的是从 db.js 的池中获取连接并使用它,然后在使用它之后释放它。

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

上面当我做 console.log("con: " + con);它显示未定义

您正在导出函数,而不是池本身。此外,getConnection 不接受任何回调:

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 (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 应该是这样的:

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

您遇到的问题是您对回调和异步调用在 JavaScript 和 Node.js 中的工作方式的理解。

理解概念检查this article

您必须将代码更改为如下所示:

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