比较好的解决方案为使用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);