node.js和mysql连接池不导出 [英] node.js and mysql connection pool does not export

查看:71
本文介绍了node.js和mysql连接池不导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在node.js中导出池连接.我想要的是从db.js的池中获取连接并使用它,然后在使用它后将其释放.

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();
})

当我执行console.log("con:" + con);时它显示未定义

above when I do console.log("con: " + con); it displays undefined

推荐答案

您正在导出的是函数,而不是池本身.此外,getConnection不接受任何回调:

You are exporting a function, not the pool itself. Besides, getConnection is not accepting any callback:

db.js应该是这样的:

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应该是这样的:

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();
});

这篇关于node.js和mysql连接池不导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆