Using LocalStorage Objects vs Web SQL Database in HTML5

In the early age of HTML5, application data was stored in cookies & included in every server request. Compare to Cookies with web storage, web applications can store data locally within the user’s browser. HTML5 Local storage is more secured and performance wise rich. Local Storage limit is larger than cookies & information is not passed on to the server, it is per origin, i.e., per domain and per protocol.

Using HTML5 LocalStorage Objects

HTML 5 storage is based on named key-value pairs. The data is stored based on a named key, retrieve using the same key, and the named key will be a string.

HTML provides 2 objects for Web Storage:

1. window.localStorage: stores data without an expiration date. The local storage will be available whenever you would use that page. Local storage will be available in the browser to all windows with the same origin (domain).

Example:

localStorage.setItem ("firstname", "John");
document.getElementById("name").innerHTML = localStorage.getItem("firstname");

2. window.sessionStorage: stores data only for a session (data will be lost when the browser is closed). Multiple windows from the same origin (URL) cannot see others session storage. Using sessionStorage object is same as localStorage object, except that it stores data for only one session.

Example: setItem (key, value) to save database key/value

sessionStorage.setItem("name", "Picasso"); /* Here name is the key, Picasso is value */
var data = sessionStorage.getItem('name');

Using Web SQL Database

The Web SQL Database API is not a part of HTML5, but is a separate specification which has a set of APIs to manipulate client side databases using SQL. It is essentially an embedded SQLite database. You can create a database, tables and run SQL on it.

HTML5 Web SQL Database Methods

There are 3 methods in SQL database which are as follows:

  • openDatabase – This method creates a database object either of the existing database or creating a new one.
  • transaction – This method helps to control a transaction and performing either commit or rollback as per the requirement.
  • executeSql – This method is used to execute the SQL query.

Opening Database

The openDatabase method creates a database or helps in opening the existing database. To create and open a database we have to do the following:

var dbs = openDatabase('mydbs', '1.0', 'test1db', 2*1024*1024);

The above method has 5 parameters – database name, version number, text description, size of database, creation callback. The creation callback parameter will be called when the database is created.

Executing Queries

To execute a query the database.transaction () function is used. This function needs a single argument which is a function which executes the query as follows:

dbs.transaction (function(tq)) {
tq.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});

The above query will create a table called LOGS in ‘mydbs’ database.

INSERT Operation

To create entries into the database table we add SQL queries as below:

var dbs = openDatabase('mydbs', '1.0', 'test1db', 2*1024*1024);
dbs.transaction (function(tq)) {
tq.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tq.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "Camera")');
tq.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "Konica")');
});

READ Operation

To read records from the database we use a callback to capture the results as shown below:

var dbs = openDatabase('mydbs', '1.0', 'test1db', 2*1024*1024);
dbs.transaction(function(tq)) {
tq.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tq.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "Camera")');
tq.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "Konica")');
});
dbs.transaction (function(tq)) {
tq.executeSql('SELECT * FROM LOGS', [ ], function(tq, result) {
var length = result.rows.length, i;
msg = "<p> Found rows: "+ length + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i=0; i<length; i++) {
alert (result.rows.item (i). log);
}
}, null);
});

Web SQL database in HTML5 vs IndexedDB

The Web SQL database is a deprecated specification since November 2010, the browser vendors are not encouraged to support this technology. The replacement is IndexedDB. It is a ‘NoSQL’ database and lets us create an Object Store for a type of data. Each Object Store can have a collection of Indexes that make it efficient to query and iterate across.

Some of the disadvantages of Web SQL are as follows:

  • Web SQL is not object-driven.
  • SQL language needs to be mastered and JavaScript objects has to be transformed into relational schema.
  • Transaction creation is explicit, default is to rollback unless we call commit.

Advantages of IndexedDB over Web SQL:

  • Allows fast indexing and searching of objects, so you can manage your data and read/write it fast.
  • Indexing of JavaScript objects based on your application needs.
  • Granular locking per transaction, which allows us to work inside the event-driven JavaScript module.

Conclusion

As Web SQL is deprecated, the web developers are recommended to stop using this technology in new projects, as the spec will not receive new updates. As a ‘NoSQL’ database, IndexedDB provides us a lot of power as it is different from relational database. Web Storage technique provides rich query abilities and is available both in offline and online mode, and can used to store large amount of data.