admin管理员组

文章数量:1327687

While developing my Cordova hybrid application, I have grown very accustomed to testing my application in a regular desktop browser, and this has worked out very well so far.

Now I'd like to add sqlite functionality to my application. I see that there is a plugin for cordova, but I am curious, how can I write a fallback so that if cordova is not being used, I can use sqlite naturally without using the cordova plugin? Ideally, I'd like it to be abstracted so that the native sqlite object behaves exactly like the plugin, so I can do all of my testing in a regular browser to minimize the number of times I have to install my app to an actual device - the build time for android is very long, so I'd like to avoid it as much as possible.

Thanks!

While developing my Cordova hybrid application, I have grown very accustomed to testing my application in a regular desktop browser, and this has worked out very well so far.

Now I'd like to add sqlite functionality to my application. I see that there is a plugin for cordova, but I am curious, how can I write a fallback so that if cordova is not being used, I can use sqlite naturally without using the cordova plugin? Ideally, I'd like it to be abstracted so that the native sqlite object behaves exactly like the plugin, so I can do all of my testing in a regular browser to minimize the number of times I have to install my app to an actual device - the build time for android is very long, so I'd like to avoid it as much as possible.

Thanks!

Share asked Mar 2, 2015 at 18:54 kenken 891 silver badge5 bronze badges 3
  • First: Why don't you try emulator? second: build time is not that much! it took nearly 20-40 seconds. third: you can try ripple emulator. chrome.google./webstore/detail/ripple-emulator-beta/… I haven't used it. But heard that you could actually run it in browser to test phonegap apps. – AtanuCSE Commented Mar 2, 2015 at 21:01
  • 1 You can use WebSQL on desktop browser. The interface(API) is the same whether you use it in cordova or desktop browser. The underlying database used can be SQLite, but it depends on the browser. Check this link for WebSQL support among desktop browsers. – frank Commented Mar 3, 2015 at 6:52
  • Great question - I see no one has provided an answer. Did you get anywhere on your own? – u01jmg3 Commented Aug 19, 2017 at 20:16
Add a ment  | 

2 Answers 2

Reset to default 2

You can use a simple wrapper which uses WebSQL for the browser and SQLite for the device. Just use different Database object. WebSQL and SQLite API is close to identical. You only need different initialization for browser and device.

Here is my example code(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);
        });
    });
});

Here is the solution that works for me based on the answer of Дмитрий Васильев

if (navigator.userAgent.match(/(Android)/)) {
    db = window.sqlitePlugin.openDatabase({name: 'mydb.db', location: 'default' }, function (db) {}, function (error) { console.log('Open database ERROR: ' + JSON.stringify(error)); });          
    console.log('DB: SQLite');

}else {

    db = window.openDatabase('mydb', "0.1", "mydb description", 200000);    
    console.log('DB: WebSQL');
}

What happen here is that if the Android device is detected, the db object will switch to SQLITE or else if it is the browser, it will use WebSql.

To detect more devices you could use this:

if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
    db = window.sqlitePlugin.openDatabase({name: 'mydb.db', location: 'default' }, function (db) {}, function (error) { console.log('Open database ERROR: ' + JSON.stringify(error)); });          
    console.log('DB: SQLite');

}else {

    db = window.openDatabase('mydb', "0.1", "mydb description", 200000);    
    console.log('DB: WebSQL');
}

All you have to do is then run your code as normal and the db object will use the right database type.

本文标签: javascriptHow do I use sqlite with cordova while testing in a normal desktop browserStack Overflow