本人学习node是先学习node中的pomelo游戏框架,个人觉得它连接mysql的比较好。使用连接池,控制连接数在10个。所以将node 连接 mysql代码献上,希望对大家有帮助。
数据库连接池dao-pool.js
var _poolModule = require('generic-pool');
/*
* Create mysql connection pool.
*/
var createMysqlPool = function() {
return _poolModule.Pool({
name: 'mysql',
create: function(callback) {
var mysql = require('mysql');
var client = mysql.createConnection({
host: 'localhost',
user: '数据库用户名',
password: '数据库连接密码',
database:'数据库名',
port: 3306
});
callback(null, client);
},
destroy: function(client) {
client.end();
},
max: 10,
idleTimeoutMillis : 30000,
log : false
});
};
exports.createMysqlPool = createMysqlPool;
数据库配置文件mysql.js
// mysql CRUD
var sqlclient = module.exports;
var _pool;
var NND = {};
/*
* Init sql connection pool
* @param {Object} app The app for the server.
*/
NND.init = function(){
_pool = require('./dao-pool').createMysqlPool();
};
/**
* Excute sql statement
* @param {String} sql Statement The sql need to excute.
* @param {Object} args The args for the sql.
* @param {fuction} cb Callback function.
*
*/
NND.getPool = function()
{
return _pool;
};
NND.query = function(sql, args, cb){
_pool.acquire(function(err, client) {
if (!!err) {
console.error('[sqlqueryErr] '+err.stack);
return;
}
client.query(sql, args, function(err, res) {
_pool.release(client);
cb(err, res);
});
});
};
/**
* Close connection pool.
*/
NND.shutdown = function(){
_pool.destroyAllNow();
};
/**
* init database
*/
sqlclient.init = function(app) {
if (!!_pool){
return sqlclient;
} else {
NND.init(app);
sqlclient.insert = NND.query;
sqlclient.update = NND.query;
sqlclient.delete = NND.query;
sqlclient.query = NND.query;
return sqlclient;
}
};
/**
* shutdown database
*/
sqlclient.shutdown = function(app) {
NND.shutdown(app);
};
调用操作如下例子
var util = require('../util/utils');
var dbclient = require('./mysql/mysql').init();//调用mysql模块
var balanceDao = module.exports;
balanceDao.selectBalance = function(sellerId, cb)
{
var sql = 'select * from balance where seller_id = ?';
var args = [sellerId];
dbclient.query(sql, args, function(err, res) //执行数据库查找
{
if(err || !res|| res.length < 0)
{
util.invokeCallback(cb, false, res);
}else
{
util.invokeCallback(cb, true, res);
}
});
};