Question

I'm working on a mobile HTML based app that uses WebSQL to store user data. Being WebSQL, the DB is stored locally on the client on the mobile. The app is used in an offline environment.

I need to add a function to export the data so that it can be sent back to a server as an .sql file when the app has internet connection at a later time.

This is my first time working with WebSQL and I am trying to do something similar to a mysqldump. Is this possible? or is there a way to mimic this functionality with WebSQL?

Was it helpful?

Solution

I blogged about this last month (http://www.raymondcamden.com/index.cfm/2014/2/24/Creating-a-data-backup-of-a-WebSQL-database), but since SO frowns on just sharing solutions, I'll post some of the code here. ;) The basic premise is:

You go through each table. You select *. You take the rows of data and then you convert them to a string.

Here is code I used to get the data.

function backup(table) {
var def = new $.Deferred();
db.readTransaction(function(tx) {
    tx.executeSql("select * from "+table, [], function(tx,results) {
        var data = convertResults(results);
        console.dir(data);
        def.resolve(data);
    });
}, dbError);

return def;
}

$(document).on("click", "#doBackupBtn", function(e) {
e.preventDefault();
console.log("Begin backup process");

$.when(
    backup("notes"), 
    backup("log")
).then(function(notes, log) {
    console.log("All done");
    //Convert to JSON
    var data = {notes:notes, log:log};
    var serializedData = JSON.stringify(data);
    console.log(serializedData);
});

});

The very last two lines are what you would tweak. For me I wanted JSON so I used native JSON serialization. If you wanted SQL you would need to loop over the lines of data and generate INSERT statements. You may be better off doing that on the server side though.

I forgot to include this utility. It simply converts SQLResultSet objects into an easier array.

//Generic utility
function convertResults(resultset) {
var results = [];
for(var i=0,len=resultset.rows.length;i<len;i++) {
    var row = resultset.rows.item(i);
    var result = {};
    for(var key in row) {
        result[key] = row[key];
    }
    results.push(result);
}
return results;
}

OTHER TIPS

I had a partial solution a few years back and now I've packaged it into a self-contained library.

Feel free to download websqldump.js on:

https://github.com/sdesalas/websqldump

There are a few options there but should should be able to export your database and post it to a remote server as follows:

// Export database and POST to remote server
websqldump.export({
  database: 'NorthwindLite',
  success: function(sql) {
    $.ajax({type: 'POST', url: 'http://myserver.com/sync', data: sql});
  }
});

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top