Node Mysql操作封装

由于最近要写个签到系统,频繁的操作mysql导致代码量暴涨,就想着优化下SQL的结构,减少工作量。

'use strict';
var mysql = require('mysql');
// 数据库配置
module.exports = {
    /**
     * 数据库配置
     */
    config: {
        host: 'localhost',
        port: 3306,
        database: 'database',
        user: 'root',
        password: 'root'
    },
    conn: null,
    /**
     * 创建连接池并连接
     * @param callback
     */
    openConn: function (callback) {
        var me = this;
        me.conn = mysql.createConnection(me.config);
    },
    /**
     * 释放连接池
     * @param conn
     */
    closeConn: function () {
        var me = this;
        me.conn.end(function (err) {
            console.log(err);
        });
    },
    /**
     * 执行连接
     * @param config
     */
    exec: function (config) {
        const me = this;
        me.openConn();
        me.conn.query(config.sql, config.params, function (err, res) {
            if (err) {
                console.log(err);
            } else if (config.callback) {
                config.callback(res);
            }
            // 关闭数据库连接
            me.closeConn();
        });
    }
};

//test
var mysqlHandler = require('mysqlHandler');
mysqlHandler.exec({
    sql: 'select * from table where id = ?',
    params: [id],
    callback: function (r) {
        console.log(r);
    }
});

猜你喜欢

转载自blog.csdn.net/u014264373/article/details/83898655