Angular4+NodeJs+MySQL 入门-02 MySql操作类

NodeJs操作MySQL类

此类封装了几个常用的方法:插入,更新,删除,查询,开启事务,事务提交,事务回滚等操作。有一这个类,操作MYSQL就方便多了。

批处理,存储过程等方法还没有添加,因为觉得目前写的那里还没有用到批处理的,所以就没有在这里加上,等以后要是用到了要进行批处理的时候,再加上。

以前用C#在操作数据库的时候,也都有类似的操作类:MSSQLHelper,OracleHelper,MySQLHelper等这些,现在只是用NodeJs写了一个操作MySql,想操作其它数据库,按照这样的思路也应该可以写出来吧。

具体怎么用在以后再讲了,如果心急的话,可以到我的 github(https://github.com/xiaotuni/angular-map-http2)里下载项目,运行起来就可以了。

const mysql = require('mysql');

/**
 * 操作类型,插入,更新,删除,查询
 */
const OperatorType = {
  Insert: 0,
  Update: 1,
  Delete: 2,
  QueryList: 3,
  QueryOne: 4,
}

/**
 * 数据操作类
 * QueryOne、Query、InsertSQL、DeleteSQL、UpdateSQL、BeginTransaction、Rollback、Commit
 * 
 * @class MySqlHelper
 */
class MySqlHelper {

  constructor() {
    this.__CreatePool();
  }

  /**
   * 创建一个资源池
   * 
   * @memberof MySqlHelper
   */
  __CreatePool() {
    this.pool = mysql.createPool({
      connectionLimit: 10,
      host: 'localhost', // 数据库连接
      user: 'liaohb',    // 数据库名用户名
      password: 'xiaotuni', // 密码
      database: 'nodejs'   // 表空间
    });
  }

  /**
   * 资源池信息
   * 
   * @param {any} error 出错事件出得函数
   * @returns 
   * @memberof MySqlHelper
   */
  poolInfo(error) {
    if (!this.pool) {
      this.__CreatePool();
    }
    if (!this.pool) {
      error && error({ code: 500, msg: '数据库连接失败' });
      return null;
    }
    return this.pool;
  }
  /**
   * 插入操作
   * 
   * @param {any} sql 插入语句
   * @param {any} success 成功后调用的方法
   * @param {any} error 失败后调用的方法
   * @memberof MySqlHelper
   */
  Query(sql, success, error) {
    this.__ExecuteSQL(sql, success, error, OperatorType.QueryList);
  }
  /**
   * 查询操作,获取一条语句
   * 
   * @param {any} sql 插入语句
   * @param {any} success 成功后调用的方法
   * @param {any} error 失败后调用的方法
   * @memberof MySqlHelper
   */
  QueryOne(sql, success, error) {
    this.__ExecuteSQL(sql, success, error, OperatorType.QueryOne);
  }
  /**
   * 更新操作
   * 
   * @param {any} Sql 修改语句
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @memberof MySqlHelper
   */
  UpdateSQL(Sql, Success, Error) {
    this.__ExecuteSQL(Sql, Success, Error, OperatorType.Update);
  }

  /**
   * 插入操作
   * 
   * @param {any} Sql 插入语句
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @memberof MySqlHelper
   */
  InsertSQL(Sql, Success, Error) {
    this.__ExecuteSQL(Sql, Success, Error, OperatorType.Insert);
  }

  /**
   * 删除操作
   * 
   * @param {any} Sql 删除语句
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @memberof MySqlHelper
   */
  DeleteSQL(Sql, Success, Error) {
    this.__ExecuteSQL(Sql, Success, Error, OperatorType.Delete);
  }

  /**
   * 执行SQL语句
   * 
   * @param {any} Sql SQL语句
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @param {any} Type 类型[查询,更新,删除,修改等]
   * @returns 
   * @memberof MySqlHelper
   */
  __ExecuteSQL(Sql, Success, Error, Type) {
    const __self = this;
    const __ProcessResult = (__sql, result, fields, Type) => {
      const _type = Type || OperatorType.QueryOne;
      let __result = result;
      switch (Type) {
        case OperatorType.Insert:
          const { insertId } = result;
          __result = { insertId };
          break;
        case OperatorType.Delete:
          break;
        case OperatorType.Update:
          break;
        case OperatorType.QueryList:
          break;
        case OperatorType.QueryOne:
          __result = result && result.length > 0 ? result[0] : null;
          break;
      }
      return __result;
    };
    const { IsBeginTrConn, BeginTrConn } = this;
    if (!!IsBeginTrConn) {
      console.log('事务线程ID:', BeginTrConn.threadId);
      // 事务处理
      BeginTrConn.query(Sql, (err, result, fields) => {
        if (err) {
          __self.Rollback(err);
          Error && Error(err);
          return;
        }
        const __result = __ProcessResult(Sql, result, fields, Type);
        Success && Success({ fields, result: __result });
      });
    } else {
      const poolInfo = this.poolInfo(Error);
      if (!poolInfo) {
        return;
      }
      const __query = poolInfo.query(Sql, (err, result, fields) => {
        if (err) {
          Error && Error(err);
          return;
        }
        const __result = __ProcessResult(__query.sql, result, fields, Type);
        Success && Success({ fields, result: __result });
      });
    }
  }

  /**
   * 开启事务
   * 
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @returns 
   * @memberof MySqlHelper
   */
  BeginTransaction(Success, Error) {
    const poolInfo = this.poolInfo(Error);
    if (!poolInfo) {
      return;
    }
    const __self = this;
    poolInfo.getConnection((err, conn) => {
      if (err) {
        Error && Error(err);
      }
      conn.beginTransaction((btErr) => {
        if (btErr) {
          Error && Error(btErr);
        }
        console.log('开始事务处理...');
        __self.BeginTrConn = conn;
        __self.IsBeginTrConn = true;
        Success && Success();
      });
    });
  }

  /**
   * 事务回滚
   * 
   * @param {any} ErrorInfo 回滚出错信息
   * @returns 
   * @memberof MySqlHelper
   */
  Rollback(ErrorInfo) {
    const { IsBeginTrConn, BeginTrConn } = this;
    const __self = this;
    if (!IsBeginTrConn) {
      return;
    }
    if (!BeginTrConn) {
      return;
    }

    console.log('Rollback->事务线程ID:', BeginTrConn.threadId);
    BeginTrConn.rollback(() => {
      console.log('事务回滚,回滚原因:', ErrorInfo);
      delete __self.IsBeginTrConn;
      delete __self.BeginTrConn;
    });
  }

  /**
   * 提交事件
   * 
   * @param {any} Success 成功后调用的方法
   * @param {any} Error 失败后调用的方法
   * @returns 
   * @memberof MySqlHelper
   */
  Commit(Success, Error) {
    const { IsBeginTrConn, BeginTrConn } = this;
    const __self = this;
    if (!IsBeginTrConn) {
      return;
    }
    if (!BeginTrConn) {
      return;
    }
    BeginTrConn.commit((err) => {
      if (err) {
        console.log('事务提交失败,执行回滚操作...');
        __self.Rollback(err);
        Error && Error(err);
        return;
      }
      console.log('事务提交成功...');
      console.log('Commit->事务提交成功...事务ID:', BeginTrConn.threadId);
      delete __self.IsBeginTrConn;
      delete __self.BeginTrConn;
      Success && Success();
    });
  }

  /**
   * 关闭连接池
   * 
   * @param {any} Success 
   * @param {any} Error 
   * @returns 
   * @memberof MySqlHelper
   */
  ClosePool(Success, Error) {
    const __self = this;
    const poolInfo = this.poolInfo(Error);
    if (!poolInfo) {
      return;
    }
    poolInfo.end((err) => {
      if (err) {
        Error && Error(err);
        return;
      }
      Success && Success();

      if (__self.__pool) {
        delete this.pool;
        delete this.__pool;
      }
    });
  }
}

module.exports = MySqlHelper;
原文地址:https://www.cnblogs.com/xiaotuni/p/7208843.html