澄清phonegap中的数据库交互(使用W3C Web SQL)

时间:2011-08-27 10:54:55

标签: cordova web-sql

我有以下一组功能,我从phonegap api(http://docs.phonegap.com/phonegap_storage_storage.md.html#Database)改编而来:

function onDeviceReady() {
         //Phonegap is ready. Open up the database and fill with data
        //
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        db.transaction(populateDB, errorCB, successCB);

}


    // Transaction success callback
    //
    function successCB() {
        //Database opened succesfully - now choose the database again
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        //Execute an SQL transaction against it. The successful results of
        //this transaction will be in querySuccess function below
        db.transaction(queryDB, errorCB);
    }

    // Transaction error callback
    //
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    // Populate the database 
    //
    function populateDB(tx) {
        tx.executeSql('DROP TABLE IF EXISTS PAGES');
        tx.executeSql('CREATE TABLE IF NOT EXISTS PAGES (id unique, data)');
        tx.executeSql('INSERT INTO PAGES (id, data) VALUES (1, "First  page")');
        tx.executeSql('INSERT INTO PAGES (id, data) VALUES (2, "Second  page")');
    }

    // Query the database
    //
    function queryDB(tx) {
        tx.executeSql('SELECT * FROM PAGES', [], querySuccess, errorCB);
    }


    // Query the success callback
    //
    function querySuccess(tx, results) {
        var len = results.rows.length;
        alert("DEMO table: " + len + " rows found.");
        for (var i=0; i<len; i++){
            alert("Row = " + i + " ID = " + results.rows.item(i).id + " Data =  " + results.rows.item(i).data);
        }
    }

看着那个。我是否正确地说每次加载应用程序时都会创建数据库?这对我来说没有意义,但也许这是唯一的方法呢?除非我编码错误

1 个答案:

答案 0 :(得分:0)

不是直接在open调用下调用populate方法,而是将事件侦听器附加到db的 load 事件。

var db = null;

 function openDB() {db = ... };

.
.
.

 if (db != null)
         addEventListener('load', loaded, false);

然后使用db.load事件的eventhandler中的初始数据填充数据库。