Sqlite的js编辑库-sql.js

dhso
2017/04/11 16:14
统计中

npm安装

npm install sql.js

npm地址

https://www.npmjs.com/package/sql.js

github&文档地址

Github
Document

示例

const path = require('path')
const fs = require('fs');
const sql = require('sql.js');

function getPath() {
  let pathArr = Array.prototype.slice.call(arguments);
  pathArr.unshift(__dirname);
  return path.join(pathArr.join('/'));
}

/**
SQL
**/
function sql(path) {
  this.path = path;
  this.db;
}
sql.prototype = {
  init: function() {
    let filebuffer = fs.readFileSync(this.path);
    let database = new sqljs.Database(filebuffer);
    this.db = database;
  },
  find: function(_sql, _params) {
    let stmt = this.db.prepare(_sql),
      res = [];
    stmt.bind(_params);
    while (stmt.step()) {
      res.push(stmt.getAsObject());
    }
    stmt.free();
    return res;
  },
  findOne: function(_sql, _params) {
    return this.find(_sql, _params)[0];
  },
  run: function(_sql, _params) {
    return this.db.run(_sql, _params);;
  }
};

(function() {
  const SQL = new sql(getPath('data', 'app.sqlite'));
  SQL.init();
  let res = SQL.find("select * from user");
  console.log(res);
})();

本文为 dhso 原创

发布在 http://blog.minws.com/sqlitede-jsbian-ji-ku-sql-js/

如有转载,请标明来源!

作者信息
姓名:dhso
热评文章
最新评论
文章概览