扫一扫分享
sql.js是SQLite到Webassembly的一个端口,通过使用Emscripten编译SQLite C代码。它使用存储在内存中的虚拟数据库文件,因此不会保留对数据库所做的更改。但是,它允许您导入任何现有的sqlite文件,并将创建的数据库导出为JavaScript类型的数组。
这里没有C绑定或node-gyp编译,sql.js是一个简单的JavaScript文件,可以像任何传统的JavaScript库一样使用。如果您使用JavaScript构建本机应用程序(例如使用Electron),或者在node.js中工作,您可能更喜欢使用SQLite的本机绑定到JavaScript。
Sql.js早于WebAssembly,因此作为asm.js项目启动。它仍然支持asm.js以实现向后兼容性。
用法
var initSqlJs = require('sql.js');
// or if you are in a browser:
// var initSqlJs = window.initSqlJs;
initSqlJs().then(SQL => {
// Create a 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");
/*
[
{columns:['a','b'], values:[[0,'hello'],[1,'world']]}
]
*/
// 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'});
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']
// 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
db.create_function("add_js", add);
// Run a query in which the function is used
db.run("INSERT INTO hello VALUES (add_js(7, 3), add_js('Hello ', 'world'));"); // Inserts 10 and 'Hello world'
// 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();
});
手机预览