我无法在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);它显示未定义的
答案 0 :(得分:5)
您正在导出函数,而不是池本身。此外,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();
});
答案 1 :(得分:2)
您遇到的问题是您对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();
})
});