Skip to content

Persisting a Modified Database

Sandi Laufenberg edited this page Nov 22, 2016 · 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")));

Example

See: http://kripken.github.io/sql.js/examples/persistent.html

Note

Here is an article showing a bit of code serving as a wrapper / adapter to the above code. The author states his code simplifies persistence of data.

See: http://cstruter.com/blog/398

-svranch

------------ end of Note --------------