node 写sql的一个封装

class MakeBaseSqlStr {
  constructor(envValue) {
    this.envValue = envValue;
    this.sqlStr = "";
  }
  makePagingSql(pageSize, pageNum) {
    this.sqlStr += ` limit ${(pageNum - 1) * pageSize},${pageSize}`;
    return this;
  }
  getSql() {
    return this.sqlStr + "";
  }
  distinctSql(fieldName) {
    this.sqlStr += " distinct " + fieldName + " ";
    return this;
  }
  in(fieldName, values) {
    this.sqlStr += `  and  ${fieldName} in (${values.join(",")}) `;
    return this;
  }
  where(objParam = {}) {
    const obj = { ...objParam, packageName: "ky-giant" };

    if (obj && typeof obj === "object") {
      let sql = "where ";
      const keys = Object.keys(obj);
      keys.forEach((key, index) => {
        if (index === keys.length - 1) {
          sql += `${key}='${obj[key]}'  `;
        } else {
          sql += `${key}='${obj[key]}' and  `;
        }
      });
      this.sqlStr += sql;
    } else {
      this.sqlStr += " ";
    }
    return this;
  }

  groupBy(name) {
    this.sqlStr += `group by ${name}`;
    return this;
  }
  select(queryContents) {
    const tableName = this.envValue === "prod" ? "cmpttable_prod" : "cmpttable";
    let sql = "select ";
    queryContents.forEach((key) => {
      sql += `${key},`;
    });
    sql = sql.substr(0, sql.length - 1);
    sql += ` from ${tableName} `;
    this.sqlStr += sql;
    return this;
  }

  reSetSql() {
    this.sqlStr = "";
    return this;
  }
}

module.exports = MakeBaseSqlStr;

一个连接数据库的封装

class OptMySql {
  constructor({ isDev }) {
    const mysql = require("mysql");
    this.connectionPool = mysql.createPool({
      host: "100.xx.172.xx",
      user: "opadmin",
      password: "sxxxx",
      database: "cpt_stat",
    });
    if (isDev) {
      // 如果是测试,就采用这个表名
      this.tableName = "cmpttable";
    } else {
      this.tableName = "cmpttable_prod";
    }
  }

  insertData(data) {
    const keyValues = Object.entries(data);
    const sql = `INSERT INTO ${this.tableName} (${keyValues
      .map((key) => `${key[0]}`)
      .join(",")}) VALUES(${keyValues.map((val) => `'${val[1]}'`).join(",")})`;

    return this.querySql(sql);
  }

  connection() {
    return new Promise((success, fail) => {
      this.connectionPool.getConnection((err, conn) => {
        if (err) {
          fail(err);
        } else {
          success(conn);
        }
      });
    });
  }

  querySql(sqlStr) {
    return new Promise((success, fail) => {
      this.connection().then((conn) => {
        conn.query(sqlStr, (err2, res) => {
          if (err2) {
            fail(err2);
          } else {
            conn.release();
            success(res);
          }
        });
      });
    });
  }

  closeDataBase() {
    this.connectionPool.end();
  }
}

module.exports = new OptMySql({});

你可能感兴趣的:(node 写sql的一个封装)