過去一段時間因爲要弄一個有趣的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);