配置文件
$ vim /game-server/config/mysql.json
{
"development": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password":"root",
"charset": "utf8mb4",
"database": "pomelo",
"connectionLimit": 10
},
"production": {
"host": "127.0.0.1",
"port": 3306,
"user": "root",
"password":"root",
"charset": "utf8mb4",
"database": "pomelo",
"connectionLimit": 10
}
}
封装类库
$ vim game-server/utils/mysql.js
const mysql = require("mysql");
let Module = function(app){
this.app = app;
if(!app.mysqlConfig){
console.log("mysql config is null");
return;
}
this.pool = mysql.createPool(app.mysqlConfig);
};
Module.prototype.query = function(sql, values){
return new Promise((resolve, reject)=>{
pool.getConnection((error, connection)=>{
if(error){
reject(error);
}else{
if(values){
connection.query(sql, values, (err, rows)=>{
if(err){
reject(err);
}else{
if(rows.length===1){
rows = rows[0];
}
resolve(rows);
}
});
}else{
connection.query(sql, (err, rows)=>{
if(err){
reject(err);
}else{
if(rows.length===1){
rows = rows[0];
}
resolve(rows);
}
});
}
connection.release();
}
});
});
};
module.exports = function(app){
return new Module(app);
};
全局配置
$ vim app.js
app.configure("production|development", function(){
//加载数据库配置
app.loadConfig("mysqlConfig", app.getBase()+"/config/mysql.json");
//初始化数据库连接对象
app.set("mysql", require(app.getBase()+"/utils/mysql.js"));
});