123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- "use strict";
- var Mysql = require('mysql');
- var configs = require('../../conf/config.inc.js');
- var AppErrors = require('./AppErrors.js');
- var objPools = {};
- /**
- * 基本类,提供增删改查
- * @param {string} dbKey
- */
- class OujMySql {
- constructor(dbKey) {
- this.dbKey = dbKey || 'default';
- }
- getPool() {
- if (!objPools[this.dbKey]) {
- var config = configs.dbInfo[this.dbKey];
- if (config) {
- objPools[this.dbKey] = Mysql.createPool(config);
- } else {
- throw new AppErrors.DbError("数据库:" + this.dbKey + "没有配置");
- }
- }
- return objPools[this.dbKey];
- }
- query(sql, values) {
- let that = this;
- return new Promise(function(resolve, reject) {
- that.getPool().query(sql, values, function(err, result) {
- if (err) {
- reject(err);
- throw new AppErrors.DbError(err);
- } else {
- resolve(result);
- }
- });
- });
- };
- /**
- * 更新数据
- * @param {string} sql
- */
- update(sql) {
- return this.query(sql, []);
- };
- /**
- * 获取一个值
- * @param {string} sql
- * @return Promise
- */
- getOne(sql) {
- var that = this;
- return new Promise(function(resolve, reject) {
- var p1 = that.getAll(sql, 1);
- p1.then(function(rows) {
- var row = rows[0];
- var val = null;
- if (row) {
- var keys = Object.keys(row);
- val = keys && row[keys[0]];
- }
- resolve(val);
- }, reject);
- });
- };
- /**
- * 获取一列数据
- * @param sql
- * @param limit 行数
- */
- getCol(sql, limit) {
- let that = this;
- return new Promise(function(resolve, reject) {
- var p1 = that.getAll(sql, limit);
- p1.then(function(rows) {
- var cols = [];
- if (rows[0] && rows.length) {
- var keys = Object.keys(rows[0]);
- let key = keys[0];
- for (var i = 0; i < rows.length; i++) {
- cols.push(rows[i][key]);
- }
- }
- resolve(cols);
- }, reject);
- });
- };
- /**
- * 获取一行数据
- * @param sql
- */
- getRow(sql) {
- let that = this;
- return new Promise(function(resolve, reject) {
- var p1 = that.getAll(sql, 1);
- p1.then(function(rows) {
- resolve(rows[0] || null);
- }, reject);
- });
- };
- /**
- * 获取所有行数据
- * @param sql
- * @param limit 行数
- */
- getAll(sql, limit) {
- if (typeof limit == 'number' && limit > 0) {
- sql += " LIMIT " + limit;
- }
- return this.query(sql, []);
- };
- /**
- * 关闭连接池
- */
- close() {
- return new Promise(function(resolve, reject) {
- this.getPool().end(function(err) {
- if (err) {
- reject(err);
- } else {
- resolve();
- }
- });
- });
- };
- }
- module.exports = OujMySql;
|