最近项目需要前端直接进行数据的增删改查,于是打算在前端嵌入 SQLite。SQL.js 是一个 SQLite 的 JavaScript 移植版本,使用 Emscripten 对 SQLite 的 C 代码进行编译,将SQLite移植到 Webassembly。 它使用存储在内存中的虚拟数据库文件,因此不会保留对数据库所做的更改。 但是,它允许您导入任何现有的 SQLite 文件,并将创建的数据库导出为JavaScript类型的数组。
网上关于 SQL.js 的教程不多,而 Vue.js 项目使用 SQL.js 更是没有。经过参考官方文档和个人摸索,总结出了 Vue.js 使用 SQL.js 的步骤。
本项目采用 Vue CLI 脚手架构建,如果采用其他方式构建,步骤仅供参考。
进入 Vue.js 项目
cd your-project-directory 2. 使用 npm 或 yarn 安装 SQL.js
cnpm install sql.js --save 或
yarn add sql.js 3. 安装完后,查看目录结构
tree /F node_modules/sql.js 结果:
NODE_MODULES\SQL.JS
│ .eslintrc.js
│ .jsdoc.config.json
│ .nojekyll
│ AUTHORS
│ documentation_index.md
│ LICENSE
│ logo.svg
│ package.json
│ README.md
│
└─dist
sql-asm-debug.js
sql-asm-memory-growth.js
sql-asm.js
sql-wasm-debug.js
sql-wasm-debug.wasm
sql-wasm.js
sql-wasm.wasm
sqljs-all.zip
sqljs-wasm.zip
sqljs-worker-wasm.zip
worker.sql-asm-debug.js
worker.sql-asm.js
worker.sql-wasm-debug.js
worker.sql-wasm.js
在项目的 (和 package.json 同级的) 根目录中创建配置文件vue.config.js (如果不存在)
在vue.config.js中写入如下配置
module.exports = {
chainWebpack: config => {
config.module.rule('wasm').test(/\.wasm$/).type('javascript/auto')
}
}
在main.js中引入 SQL.js
import initSqlJs from "sql.js"
// Required to let webpack 4 know it needs to copy the wasm file to our assets
import sqlWasm from "!!url-loader?name=sql-wasm-[contenthash].wasm!sql.js/dist/sql-wasm.wasm";
2. 在中加载数据库
async function loadDB() {
try {
const SQL = await initSqlJs({
locateFile: () => sqlWasm
});
return new SQL.Database()
} catch (err) {
console.log(err);
}
}
loadDB().then(db => app.config.globalProperties.$db = db) 3. 执行 SQL 语句
api 用例来自官方文档,可以看到执行 SQL 语句的方法还是很常规的
// Prepare an sql statement
const stmt = this.$db.prepare("SELECT * FROM hello WHERE a=:aval AND b=:bval");
// Bind values to the parameters and fetch the results of the query
const result = stmt.getAsObject({':aval' : 1, ':bval' : 'world'});
console.log(result); // Will print {a:1, b:'world'}
// Bind other values
stmt.bind([0, 'hello']);
while (stmt.step()) console.log(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.
// Execute a single SQL string that contains multiple statements
let sqlstr = "CREATE TABLE hello (a int, b char);";
sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
sqlstr += "INSERT INTO hello VALUES (1, 'world');"
this.$db.run(sqlstr); // Run the query without returning anything
const res = this.$db.exec("SELECT * FROM hello");
/*
[
{columns:['a','b'], values:[[0,'hello'],[1,'world']]}
]
*/
// You can also use JavaScript functions inside your SQL code
// Create the js function you need
function add(a, b) {return a+b;}
// Specifies the SQL function's name, the number of it's arguments, and the js function to use
this.$db.create_function("add_js", add);
// Run a query in which the function is used
this.$db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world'
// Export the database to an Uint8Array containing the SQLite database file
const binaryArray = this.$db.export(); 更多用法参考官方文档:https://github.com/sql-js/sql.js