如何在浏览器中开发和测试Cordova SQLite应用程序?

问题描述 投票:0回答:1

我找到的唯一方法是使用不同的浏览器和设备适配器的PouchDB。但这种方式不适合我。

javascript sqlite cordova browser
1个回答
0
投票

使用Cordova-sqlite-storage的另一种方法只是为浏览器和设备使用不同的Database对象。

这是我的代码(ES6)的一部分:

var runiOS = false;
var DB;

// Check browser or device

var onDeviceReady = new Promise(function(resolve, reject) {    
    if (document.URL.match(/^https?:/i)) {
        console.log("Running in a browser...");
        resolve();
    } else {
        console.log("Running in an app...");
        runiOS = true;
        document.addEventListener("deviceready", resolve, false);
    }
});

// Run application
onDeviceReady.then(function() {
    //  Init WebSQL on browser or SQLite on device
    if (runiOS) {
        DB = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function (db) {}, function (error) { console.log('Open database ERROR: ' + JSON.stringify(error)); });          
        console.log('DB: SQLite');
    }
    else {
        DB = window.openDatabase('my', "0.1", "My list", 200000);    
        console.log('DB: WebSQL');
    }

    // ...

    db.transaction(function(tx) {
        tx.executeSql('CREATE TABLE IF NOT EXISTS DemoTable (name, score)');
        tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]);
        tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Betty', 202]);
    }, function(error) {
        console.log('Transaction ERROR: ' + error.message);
    }, function() {
        console.log('Populated database OK');
    });


    db.transaction(function(tx) {
        tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(tx, rs) {
            console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount);
        }, function(tx, error) {
            console.log('SELECT error: ' + error.message);
        });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.