SQL.js -- 操作sqlite数据库

发布时间 2023-03-28 09:23:28作者: jack_Meng

js -- 操作sqlite数据库

最近看到一个使用js来操作sqlite数据库的,测试了一下,具体使用的是

js操作类: https://github.com/kripken/sql.js/(sqlite js 驱动)

异步请求:http://npm.taobao.org/package/axios(异步请求插件,只有12.6k)

这里使用的js驱动是和服务器端使用方法一致,sql标准语法都支持,可以用第三方管理工具来管理数据文件

目前我使用的是 Navicat Premium 12

下面是测试的源代码:

1. 数据库sql(自己运行生成test.db,和html页面放在同一目录下):

PRAGMA foreign_keys = false;

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS "sys_user";
CREATE TABLE "sys_user" (
  "id" bigint(11) NOT NULL,
  "role_id" bigint(11) NOT NULL,
  "user_name" varchar(255) NOT NULL,
  "user_pass" varchar(64) NOT NULL,
  "nick_name" varchar(255) NOT NULL,
  "register_time" datetime NOT NULL,
  "status" int(11) NOT NULL DEFAULT 1,
  "sort" decimal(16,2) NOT NULL DEFAULT 0.00,
  PRIMARY KEY ("id")
)
WITHOUT ROWID;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO "sys_user" VALUES (1, 1, 'lxw', 123456, '李兴武', '2019-01-07 11:22:30', 0, 1);
INSERT INTO "sys_user" VALUES (2, 1, 'lwq', 123456, '浏览器', '2019-01-08 11:11:11', 0, 2);
INSERT INTO "sys_user" VALUES (3, 1, 'tjun', 123123, '田俊', '2018-01-01 12:22:35', 1, 3);
INSERT INTO "sys_user" VALUES (4, 1, 'tttt', 123456, '通天塔', '', 1, 4);

-- ----------------------------
-- Indexes structure for table sys_user
-- ----------------------------
CREATE UNIQUE INDEX "pk"
ON "sys_user" (
  "id" COLLATE BINARY ASC
);

PRAGMA foreign_keys = true;

2. html(可直接复制下来运行)

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>sqlite数据库测试</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcss.com/sql.js/0.5.0/js/sql-optimized.js"></script>
</head>
<body>

<p>sqlite数据库测试,使用js操作sqlite数据库</p>
<p>这里使用axios读取test.db文件,进行初始化数据库连接,</p>
<p>查询速度不快,除非不想写后台要直接操作数据库,不然没什么用。</p>
<p>具体效果可查看代码和控制台打印的数据。</p>

<script>

    // 读取数据库数据
    axios.get("test.db", {responseType: 'arraybuffer'})
        .then(function (response) {
            let db = new window.SQL.Database(new Uint8Array(response.data));
            // 执行查询
            let s = new Date().getTime();
            let r = db.exec("SELECT * FROM sys_user WHERE status = 1;");
            let e = new Date().getTime();
            console.info("查询数据耗时:" + (e - s) + "ms");
            // 解析数据
            let obj = dbToObj(r);
            console.info(obj);
        })
        .catch(function (error) {
            console.info(error);
        });

    // 方法传入两个数组,第一个数组为key,第二个数组对应位置为value,此方法在Python中为zip()函数。
    const ArraytoObj = (keys = [], values = []) => {
        if (keys.length === 0 || values.length === 0) return {};
        const len = keys.length > values.length ? values.length : keys.length;
        const obj = {};
        for (let i = 0; i < len; ++i) {
            obj[keys[i]] = values[i]
        }
        return obj;
    };

    // 转驼峰表示:func.camel('USER_ROLE',true) => UserRole
    // 转驼峰表示:func.camel('USER_ROLE',false) => userRole
    const camel = (str, firstUpper = false) => {
        let ret = str.toLowerCase();
        ret = ret.replace(/_([\w+])/g, function (all, letter) {
            return letter.toUpperCase();
        });
        if (firstUpper) {
            ret = ret.replace(/\b(\w)(\w*)/g, function ($0, $1, $2) {
                return $1.toUpperCase() + $2;
            });
        }
        return ret;
    };

    // 把数组里面的所有转化为驼峰命名
    const camelArr = (arrs = []) => {
        let _arrs = [];
        arrs.map(function (item) {
            _arrs.push(camel(item));
        });
        return _arrs;
    };

    // 读取数据库
    // 1.把columns转化为驼峰;
    // 2.把columns和values进行组合;
    const dbToObj = (_data = {}) => {
        let _res = [];
        _data.map(function (item) {
            let _columns = camelArr(item.columns);
            item.values.map(function (values) {
                _res.push(ArraytoObj(_columns, values));
            });
        });
        return _res;
    };
</script>
</body>
</html>

 

 

出处:https://www.cnblogs.com/lixingwu/p/10236640.html

=======================================================================================

从JavaScript访问SQLite3数据库

比较好的解决方案为使用sql.js

For the impatients, try the demo here: http://kripken.github.io/sql.js/GUI/

sql.js is a port of SQLite to JavaScript, by compiling the SQLite C code with Emscripten. It uses a virtual database file stored in memory, and thus does’nt persist the changes made to the database. However, it allows you to import any existing sqlite file, and to export the created database as a javascript typed array.

There is no C bindings or node-gyp compilation here, sql.js is a simple javascript file, that can be used like any traditional javascript library. If you are building a native application in javascript (using Electron for instance), or are working in node.js, you will likely prefer to use a native binding of SQLite to javascript.

SQLite is public domain, sql.js is MIT licensed.

以下是待验证的使用:

var db = SQL.open();
var data = db.exec(command);

详细使用方案见用JavaScript操作SQLite文件

还有一篇文章也不错
其中详细说明了怎么连接自己的数据库。
过去一段时间因为要弄一个有趣的CS架构程序,需要找一个文件型数据库,最后决定用sqlite3数据库。但是js连接sqlite3 数据库伤透了脑筋。使用nodejs连接sqlite数据库但是node的ABI与node-webkit的ABI对不上号,就快在崩溃的边缘时找到了一个比较好的连接sqlite3数据库的工具sql.js。从此变得一发不可收拾。
sql.js下载地址:https://github.com/kripken/sql.js
下面是使用sql.js写的一个demo:
需在页面上导入sql.js

         function test()

        {
            var fs = require("fs");
            //Create the database
            var db = new SQL.Database();
            // NOTE: You can also use new sql.Database(data) where
            // data is an Uint8Array representing an SQLite database file
            // Execute some sql
            sqlstr = "CREATE TABLE hello (a int, b char);";
            sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
            sqlstr += "INSERT INTO hello VALUES (1, 'world');"
            db.run(sqlstr); // Run the query without returning anything
            var res = db.exec("SELECT * FROM hello");
               // Prepare an sql statement
            var stmt = db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");
            // Bind values to the parameters and fetch the results of the query
            var result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'});
            alert(result); // Will print {a:1, b:'world'}
            // Bind other values
            stmt.bind([0, 'hello']);
            while (stmt.step()) alert(stmt.get()); // Will print [0, 'hello']
            // free the memory used by the statement
            stmt.free();
            // You can not use your statement anymore once it has been freed.
            // But not freeing your statements causes memory leaks. You don't want that.
            // Export the database to an Uint8Array containing the SQLite database file
            var binaryArray = db.export();
            var buffer = new Buffer(binaryArray);
            fs.writeFileSync("filename.sqlite", buffer);
        }

也可以使用自己新建的sqlite数据库文件
导入方式:

   var fs =require('fs');
    var filebuffer=fs.readFileSync('test.sqlite');// Load the db
    var db= new  SQL.Database(filebuffer);

    // Exportthe database to an Uint8Array containing the SQLite databasefile
       varbinaryArray = db.export();
       var buffer =new Buffer(binaryArray);
      fs.writeFileSync("test.sqlite", buffer);

 

出处:https://www.jianshu.com/p/364740cf6b75

======================================================================================