gpt4 book ai didi

mysql - node.js和mysql连接池不导出

转载 作者:可可西里 更新时间:2023-11-01 07:51:39 24 4
gpt4 key购买 nike

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

查询.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和mysql连接池不导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35914736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com