node-webkit中js连接sqlite3文件型数据库

来源:互联网 发布:手机光绘软件 编辑:程序博客网 时间:2024/06/05 14:11
过去一段时间因为要弄一个有趣的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);

0 0
原创粉丝点击