登录
注册
node.js 学习社区
使用node-mysql中的连接池

小黄桃

2014-12-13 07:32

根据原来generic-pool的例子修改过来的,这样可以少一个依赖了,哈哈
mysql-pool.js

var mysql       = require('mysql');
var mysqlConfig = require('../config/mysql');

var env = process.env.NODE_ENV || 'development';
if(mysqlConfig[env]) {
  mysqlConfig = mysqlConfig[env];
}
exports.createMysqlPool= module.exports.createMysqlPool = function(){
  return mysql.createPool({
        host: mysqlConfig.host,
        user: mysqlConfig.user,
        password: mysqlConfig.password,
        database: mysqlConfig.database
  });
}

创建一个简单的客户端链接帮助类 mysqlclient

  // mysql CRUD
var sqlclient = module.exports;

var _pool = null;

var NND = {};

/*
 * Innit sql connection pool
 * @param {Object} app The app for the server.
 */
NND.init = function(){
  if(!_pool)
    _pool = require('./mysql-pool').createMysqlPool();
};

/**
 * Excute sql statement
 * @param {String} sql Statement The sql need to excute.
 * @param {Object} args The args for the sql.
 * @param {fuction} callback Callback function.
 * 
 */
NND.query = function(sql, args, callback){
  _pool.getConnection(function(err, client) {
    if (!!err) {
      console.error('[sqlqueryErr] '+err.stack);
      return;
    }
    client.query(sql, args, function(err, res) {
      _pool.releaseConnection(client);
      callback.apply(null, [err, res]);
    });
  });
};

/**
 * Close connection pool.
 */
NND.shutdown = function(){
  _pool.end();
};

/**
 * init database
 */
sqlclient.init = function() {
  if (!!_pool){
    return sqlclient;
  } else {
    NND.init();
    sqlclient.insert = NND.query;
    sqlclient.update = NND.query;
    //sqlclient.delete = NND.query;
    sqlclient.query = NND.query;
    return sqlclient;
  }
};

/**
 * shutdown database
 */
sqlclient.shutdown = function() {
  NND.shutdown();
};

实际调用类

var utils = require('../lib/utils');
var mysqlClient = require('./mysqlcliet').init();

var orgdao = module.exports;

orgdao.queryOrgByPId = function (pid, cb){
    var sql = 'YOUR SQL';
    var args = [pid];
    mysqlClient.query(sql,args,function(err, res){
        if(err !== null){
            utils.invokeCallback(cb, err.message, null);
        } 
        else {
            if (!!res) {
                utils.invokeCallback(cb, null, res);
            }
            else{
                utils.invokeCallback(cb, null, null);
            }
        }
    });
};

原文引自:http://cnodejs.org/topic/51676ac26d38277306fe7c85

回复 · 0

发表回复

你可以在回复中 @ 其他人