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({});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章