jae-jae
11/24/2016 - 6:55 AM

M.js对NodeJS的数据库操作的简单封装

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