sql.js是一个javascript访问SQLite数据库的封装库。
项目的Github地址是:https://github.com/sql-js/sql.js
文档地址是:https://sql.js.org
源码不方便访问的,也可以从这里下载。
自己写了两个用例,第一个访问的是浏览器内存数据库,第二个是持久化的数据库文件。上代码:
let config = {locateFile: () => "/js/sql.js/dist/sql-wasm.wasm"}
initSqlJs(config).then(async function (SQL) {
//Create the database
const db = new SQL.Database();
// Run a query without reading the results
db.run("CREATE TABLE test (col1, col2);");
db.run("INSERT INTO test VALUES (?,?), (?,?)", [1, 111, 2, 222]);
// Prepare a statement
const stmt = db.prepare("SELECT * FROM test WHERE col1 BETWEEN $start AND $end");
stmt.getAsObject({$start: 1, $end: 1});
// Bind new values
stmt.bind({$start: 1, $end: 2});
while (stmt.step()) { //
const row = stmt.getAsObject();
console.log('Here is a row: ' + JSON.stringify(row));
}
});
let config = {locateFile: () => "/js/sql.js/dist/sql-wasm.wasm"}
initSqlJs(config).then(function(SQL){
const xhr = new XMLHttpRequest();
xhr.open('GET', "/data/Animation_02.sqlite", true);
xhr.responseType = 'arraybuffer';
xhr.onload = e => {
const uInt8Array = new Uint8Array(xhr.response);
const db = new SQL.Database(uInt8Array);
const contents = db.exec("SELECT * FROM AnimationVessel order by Id");
console.log(JSON.stringify(contents));
};
xhr.send();
});
以sqlite_file.js为例创建html页面文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/sql.js/dist/sql-wasm.js"></script>
<script type="module" src="/js/sqlite_file.js"></script>
</head>
<body>
</body>
</html>
在浏览器的console中即可看到相应输出。