问题
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