美文网首页
node操作数据库

node操作数据库

作者: 小仙有毒_1991 | 来源:发表于2020-09-08 10:10 被阅读0次

随着node的出现,前端通过JS操作数据库成为可能,下面分享一下当前PC前端项目中JS操作Sqlite数据库时封装的工具方法:

(function (window, document, undefined) {

  "use strict";

  var db, sqliteDB, dbPath; //db对象, sqllite对象, d当前账号对应的db数据存放路径

  var fs = window.require("fs");
  var path = window.require("path");
  var DB = window.require("sqlite3").verbose();

  /*
    封装db方法
  */
  var init = function (fPath, dbName) {
    sqliteDB = DB;
    initDataBase(fPath, dbName);
  }

  /* 根据账号初始化数据库 */
  function initDataBase(dbName) {
    if (!dbName) {
      dbName = "splite";
    }
    if (fPath) {
      dbPath = fPath;
    } else {
      dbPath = window.getUserPath() + "\\project\\data\\";
    }
    if (checkPath(dbPath)) {
      dbPath = dbPath.replace(/\\/g, "/") + "/" + dbName + ".db";
      db = new sqliteDB.Database(dbPath);
    }
  }

  /* 检测目录是否存在,不存在的话创建 */
  function checkPath(dbpath) {
    if (!fs.existsSync(dbpath)) {
      var pathtmp;
      dbpath.split(path.sep).forEach(function (dirname) {
        if (pathtmp) {
          pathtmp = path.join(pathtmp, dirname);
        } else {
          pathtmp = dirname;
        }

        if (!fs.existsSync(pathtmp)) {
          if (!fs.mkdirSync(pathtmp, 0777)) {
            return false;
          }
        }
      });
    }
    return true;
  }

  /* 链接数据库,及其执行数据库语句的方法 */
  var dbService = {
    init: init,
    connect: function (options) {
      db = new sqliteDB.Database(dbPath, sqliteDB.OPEN_READWRITE | sqliteDB.OPEN_CREATE,
        function (err) {
          if (err) {
            if (typeof options.error === 'function') {
              options.error({"errCode": "db_error", errMsg: "数据库异常"});
            }
            //console.log(err);
            return;
          }
          if (typeof options.success === 'function') {
            options.success();
          }
        }
      );
    },

    exec: function (options) {
      if (!db.open) this.connect({});
      var sqls = options.sqls;
      db.exec('begin');
      db.exec(sqls.join(';'));
      db.exec('commit',
        function (err) {
          if (err) {
            if (err.errno == 1) {
              if (typeof options.success === 'function') {
                options.success();
              }
              return;
            }
            if (typeof options.error === 'function') {
              options.error({
                "errCode": "db_error", errMsg: "数据库异常"
              });
            }
            //console.log(err);
            return;
          }
          if (typeof options.success === 'function') {
            options.success();
          }
        }
      );
    },

    /* 
      查询数据方法 
      var options = {};
      options.sql = "select * from testTable1";  
      options.success = function(data)  //必输 data 为返回的数据对象
      options.error = function(data)  //非必输 data 为返回的报错信息
    */
    select: function (options) {
      if (!db.open) dbService.connect({});
      var sql = options.sql;
      db.all(sql, function (err, rows) {
        if (err) {
          if (typeof options.error === 'function') {
            options.error({"errCode": "db_error", errMsg: lang.db_error});
          }
          //console.log(err);
          return;
        }
        if (typeof options.success === 'function') {
          options.success(rows);
        }
      });
    },

    /* 
      修改数据方法 
      var options = {};
      options.tName;  //表名称
      options.tCols;    //列名称数组
      options.tValues;  //列对应的数据数组
      options.tWhere;   // where 后的判断条件
      options.success = function(data)  //必输 data 为返回的数据对象
      options.error = function(data)  //非必输 data 为返回的报错信息
    */
    update: function (options) {
      if (!db.open) dbService.connect({});
      var t_Name = options.tName;
      var t_Cols = options.tCols;
      var t_Values = options.tValues;
      var t_Where = "";
      if (options.tWhere) {
        t_Where = " Where " + options.tWhere
      }
      var sql = "Update " + t_Name + " set " + t_Cols.join(' = ?, ') + " = " + t_Values.join(' = ?, ') + t_Where;
      console.log("sql:" + sql);

      db.run(sql, t_Values,
        function (err) {
          if (err) {
            if (err.errno == 1) {
              if (typeof options.success === 'function') {
                options.success();
              }
              return;
            }
            if (typeof options.error === 'function') {
              options.error({
                "errCode": "db_error", errMsg: "数据库异常"
              });
            }
            return;
          }
          if (typeof options.success === 'function') {
            options.success();
          }
        }
      )
    },

    /* 
      查询插入方法
      var options = {};
      假如 options.sql 存在则不需要 options.tName  options.tCols   options.tValues
      options.sql = "select * from testTable1";  
      反之如果 options.sql 不存在则需要 options.tName  options.tCols   options.tValues(多条记录对应的2维数组) 参数 均不能为空
      options.success = function()  //非必输 为成功的返回函数 没有参数
      options.error = function(data)  //非必输 data 为返回的报错信息
    */
    insert: function (options) {
      if (!db.open) dbService.connect({});
      if (!options.sql) {
        var t_Name = options.tName;
        var t_Cols = options.tCols;
        var t_Values = options.tValues;

        var sqls = [];
        for (var i = 0; i < t_Values.length; i++) {
          var sql = "insert into " + t_Name + " (" + t_Cols.join(',') + ") VALUES ('" + t_Values[i].join("','") + "')";
          sqls.push(sql);
        }
        options.sql = sqls.join(';');
      }
      console.log("insert sql:" + options.sql);
      db.exec('begin');
      db.exec(options.sql);
      db.exec('commit',
        function (err) {
          if (err) {
            if (err.errno == 1) {
              if (typeof options.success === 'function') {
                options.success();
              }
              return;
            }
            if (typeof options.error === 'function') {
              options.error({
                "errCode": "db_error", errMsg: "数据库异常"
              });
            }
            return;
          }
          if (typeof options.success === 'function') {
            options.success();
          }
        }
      );
    },

    /*
      删除数据方法 
      var options = {};
      options.tName;  //表名称
      options.tWhere;   // where 后的判断条件
      options.success = function()  //必输 data 为返回的数据对象
      options.error = function(data)  //非必输 data 为返回的报错信息
    */
    delete: function (options) {
      if (!db.open) dbService.connect({});
      var t_Name = options.tName;
      var t_Where = options.tWhere;
      var sql = "Delete From " + t_Name + " Where " + t_Where;
      db.exec('begin');
      db.run(sql);
      db.exec('commit',
        function (err) {
          console.log(JSON.stringify(err));
          if (err) {
            if (err.errno == 1) {
              if (typeof options.success === 'function') {
                options.success();
              }
              return;
            }
            if (typeof options.error === 'function') {
              options.error({
                "errCode": "db_error", errMsg: "数据库异常"
              });
            }
            return;
          }
          if (typeof options.success === 'function') {
            options.success();
          }
        }
      )
    };
}
  window.dbService = dbService;
})(window, document);

相关文章

  • nodeJs

    node.js 搭建服务 数据库常用操作 node操作数据库 案例

  • node

    数据库(database) 概念 数据库常用类型 Node 操作数据库 数据库常用操作

  • NodeJs

    NodeJs 数据库(database) 概念 数据库常用类型 Node操作数据库 数据库常用操作

  • 05-Node.js 操作 MongoDB 数据库

    Node 操作 MongoDB 数据库MongoDB 相关概念Node 操作 MongoDB 的第三方包 - mo...

  • # node操作mongodb数据库的封装

    node操作mongodb数据库的封装 最近玩node 的时候,我发现我需要个数据库,我选择了mongodb这个数...

  • 08/15 nodejs操作mongodb

    node.js 操作mongodb数据库 源代码 npmjs_mongodb

  • XDL_NO.8 Node.js 操作MongoDB数据库

    Node.js 操作MongoDB数据库 安装组件 mongodb Node.js 官方对MongoDB的驱动mo...

  • IT兄弟会全栈工程师01班第8课笔记

    本课重点:学习Node.js连接MongoDB数据库操作,并实现基本的数据库增、删、改、查操作。 1.安装Mong...

  • 0816

    node.js 操作mongodb数据库 nodejs 自带组件 mongodb/mongoose npm ins...

  • nodejs+mongodb

    nodejs操作 mongodb数据库增删改查 创建node增删改查执行文件

网友评论

      本文标题:node操作数据库

      本文链接:https://www.haomeiwen.com/subject/pirdektx.html