🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## node 中(可在单元测试中运行) ``` const initSqlJs = require('sql.js'); // or if you are in a browser: // const initSqlJs = window.initSqlJs; const SQL = await initSqlJs({ // Required to load the wasm binary asynchronously. Of course, you can host it wherever you want // You can omit locateFile completely when running in node locateFile: file => `https://sql.js.org/dist/${file}` }); // Create a database const db = new SQL.Database(); // NOTE: You can also use new SQL.Database(data) where // data is an Uint8Array representing an SQLite database file // Execute a single SQL string that contains multiple statements let sqlstr = "CREATE TABLE hello (a int, b char); \ INSERT INTO hello VALUES (0, 'hello'); \ INSERT INTO hello VALUES (1, 'world');"; db.run(sqlstr); // Run the query without returning anything // Prepare an sql statement const stmt = 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. const res = db.exec("SELECT * FROM hello"); /* [ {columns:['a','b'], values:[[0,'hello'],[1,'world']]} ] */ ``` ## 读取一个数据库 ``` const fs = require('fs'); const initSqlJs = require('sql-wasm.js'); const filebuffer = fs.readFileSync('test.sqlite'); initSqlJs().then(function(SQL){ // Load the db const db = new SQL.Database(filebuffer); }); ``` ## 写入一个数据库 ``` const fs = require("fs"); // [...] (create the database) const data = db.export(); const buffer = Buffer.from(data); fs.writeFileSync("filename.sqlite", buffer); ```