数据库
首页 > 数据库> > node.js和mysql连接池不导出

node.js和mysql连接池不导出

作者:互联网

我无法在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();
});

标签:mysql,node-js,node-mysql
来源: https://codeday.me/bug/20190727/1555711.html