我无法在node.js中导出池连接.我想要的是从db.js获取池中的连接并使用它,然后在使用它之后释放它. db.js var mySQL = require('mysql'); var pool = mySQL.createPool({ host: config.host, user: config.user, passwo
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(); });