Skip to content

Instantly share code, notes, and snippets.

@jae-jae
Last active November 24, 2016 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jae-jae/bfe0961253e7441242bb724906b26133 to your computer and use it in GitHub Desktop.
Save jae-jae/bfe0961253e7441242bb724906b26133 to your computer and use it in GitHub Desktop.
M.js对NodeJS的数据库操作的简单封装
/**
* M.js
*
* 对NodeJS的数据库操作的简单封装
*
* @author Jaeger <JaegerCode@gmail.com>
* @link https://gist.github.com/jae-jae/bfe0961253e7441242bb724906b26133
* @version 1.1
*
**/
"use strict";
/**
//database config file : config.js
var config = {
'DB_HOST' : 'localhost',
'DB_USER' : 'root',
'DB_PASSWORD' : '123456',
'DB_DATABASE' : 'test'
};
module.exports = config
**/
//数据库对外操作类
class M {
constructor(config)
{
config || (config='./config');
this.config = require(config);
this.mysql = require("mysql");
this.link = this._connect();
}
_connect(){
return this.mysql.createPool({
host : this.config["DB_HOST"],
user : this.config["DB_USER"],
password : this.config["DB_PASSWORD"],
database : this.config["DB_DATABASE"]
});
}
setTable(table){
this.table = table;
return this;
}
getTable(table){
return this.table;
}
select(where,field,callback){
field || (field = '*');
this.link.query(`select ${field} from ${this.table} where ${where}`,callback);
return this;
}
insert(data,callback){
this.link.query(`INSERT INTO ${this.table} SET ?`,data,callback);
return this;
}
update(data,where,callback){
this.link.query(`UPDATE ${this.table} SET ? where ${where}`,data,callback);
return this;
}
delete(where,callback){
this.link.query(`DELETE FROM ${this.table} WHERE ${where}`,callback);
return this;
}
end(){
this.link.end();
}
}
module.exports = new M()

M.js用法

安装依赖

npm install mysql

创建数据库配置文件 config.js

M.js同级目录创建数据库配置文件config.js,内容如下:

var config = {
    'DB_HOST' : 'localhost',
    'DB_USER' : 'root',
    'DB_PASSWORD' : '123456',
    'DB_DATABASE' : 'test'
};

module.exports = config

例子

"use strict";
//引用M.js
const M = require('./M');
//设置当前使用的数据表
M.setTable('user');

1.增

M.insert({name:'Mr.One',age:123},function(err, results){
    console.log(err, results);
});

2.删

M.delete('id = 1');

3.改

M.update({name:'Mr.Two'},'id = 2');

4.查

M.select('id > 2','name,age',function(err, rows){
    console.log(err, rows);
});

5.关闭数据库连接

M.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment