Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6+thunkify封装和使用 node.js的mysql模块 #6

Open
chenshenhai opened this issue Jun 10, 2016 · 1 comment
Open

ES6+thunkify封装和使用 node.js的mysql模块 #6

chenshenhai opened this issue Jun 10, 2016 · 1 comment
Labels

Comments

@chenshenhai
Copy link
Owner

chenshenhai commented Jun 10, 2016

ES6+thunkify封装和使用 node.js的mysql模块

利用ES6 class 语法重新封装mysql模块

databaseUtil.js

const config = require("./../../config") 
const mysql = require("mysql")

//配置数据库参数
const pool = mysql.createPool({
    host     :  config["DB_HOST"],
    user     : config["DB_USER"],
    password : config["DB_PASSWORD"],
    database : config["DB_DATABASE"]
});    

//数据库基本操作方法
const query = function ( sql, values, callback ) {
    pool.getConnection(function(err, conn) {
        if (err) {
            callback(err, false)
        } else {
            var querys = conn.query(sql, values, function(err, rows) {

                if (err) {
                    callback(err, false)
                } else {
                    callback(null,rows)
                }
            }); 
        }
    });
}

//数据库对外操作类
class DatabaseUtil {

    //建表方法
    createTable ( sql, callback ) {
        query( sql, [], callback )
    }

    //根据id查找数据
    findDataById ( table,  id, callback) {
        let  _sql =  "select * from ?? where id = ? "
        query( _sql, [ table, id, start, end ], callback )
    }

    //分页查找数据
    findDataByPage ( table, start, end , callback) {
        let  _sql =  "select * from ??  limit ? , ?"
        query( _sql, [ table,  start, end ], callback )
    }

    //插入数据
    insertData ( table, values, callback ) {
        let _sql = "insert into ?? set ?"
        query( _sql, [ table, values ], callback )
    }

    //更新数据
    updateData ( table, values, id,  callback ) {
        let _sql = "update ?? set ? where id = ?"
        query( _sql, [ table, values, id ], callback )
    }

    //删除数据
    deleteDataById ( table, id, callback ) {
        let _sql = "delete from ?? where id = ?"
        query( _sql, [ table, id ], callback )
    }
}


module.exports = DatabaseUtil

利用thunkify封装方法并使用

const co = require("co")
const thunkify = require("thunkify")
const DatabaseUtil = require("./databaseUtil")
const createTable = thunkify( DatabaseUtil .createTable )



co(function *(){
    let sql = 'create .... '
    let result = yield createTable( sql ); 

}).catch(function onerror(err) {
  console.error(err.stack);
});
@DuncanXiao
Copy link

如果数据回滚呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants