Skip to content

Persisting a Modified Database

Ophir LOJKINE edited this page Jun 13, 2014 · 7 revisions

If your database is in the array dbFile and you open it with db = SQL.open(dbFile) the dbFile array will contain the modified database. It is possible to save the dbFile by stringifying it then sending it back to the originating server or saving it in local storage with localStorage['localSQLiteDB'] = strdb;.

Save a database to a string

Here, we save the db to localStorage:

function toBinString (arr) {
	var uarr = new Uint8Array(arr);
	var strings = [], chunksize = 0xffff;
	// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
	for (var i=0; i*chunksize < uarr.length; i++){
		strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
	}
	return strings.join('');
}

window.localStorage.setItem("mydata", toBinString(db.export()));

Load from a string

Use the following to load a database from localStorage:

function toBinArray (str) {
	var l = str.length,
			arr = new Uint8Array(l);
	for (var i=0; i<l; i++) arr[i] = str.charCodeAt(i);
	return arr;
}
var db = new SQL.Database(toBinArray(localStorage.getItem("mydata")));