ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Computer Programming Tutorials

List: 3 Types of HTML 5 Database and Storage Options | HTML5 Database

Updated on October 26, 2011

The new HTML5 specification offers developers several new data storage features allowing them to create apps that begin to rival their offline (aka desktop) counterparts. These new features allow developers to take their apps “offline” allowing users to store information on their local computers, tablets, smartphones and other “smart” devices.

To some savvy developers this also means being able to circumvent the “Walled Gardens” of Apple, Google or others which demand a percentage of the sale of an app. At the time of this writing, Google and Apple were charging 30% of the sale of an app. However, this only applies to installed apps, not web apps that are installed in the browser.

So what the options for storage under the new HTML5 specification?

  • Web SQL
  • Web Storage
  • Indexed Database


Lets start with Web SQL. This api uses the SQLite database engine to store information on your hard drive in the form of a sql database. To date, and this will probably stay this way or regress, only Google Chrome, Apple Safari and Opera support the HTML5 Web SQL. At the time of this writing all maintenance has been halted( by the on November 18, 2010 because they need a more independent implementation and not use the SQLite database engine.

Web SQL allows developers to use SQL to create, open, query and store data in a relational database format. This api, although no longer supported by is still available to developrs who want to create “installable” apps for Chrome or Safari or Opera.

Here are some examples:

To initialize and create a database

var db = openDatabase('sampledb', '1.0', 'A test html5 database', 2 * 1024 * 1024, createInitTable);

The openDatabase method takes four parameters:

  • The database name;
  • The version;
  • The database title;
  • The database size;
  • The Callback function;

If the database doesn’t exist, it is created, otherwise it is opened. Once open, it calls the createInitTable function or whatever function you need if the database hasn’t been created yet.

Once you have a handle on the database, you can use the executeSql function to parse in any valid SQL statement.

To create a table:

	tx.executeSql('CREATE TABLE IF NOT EXIST foo (id, column1, column2)');


//Once the table is created, you can add some rows like so:

	tx.executeSql('CREATE TABLE IF NOT EXIST foo (id, column1, colum2)');
tx.executeSql('INSERT INTO foo (id, column1, column2) VALUES (?, ?, ?)', [id, value1, value2]);


You could just as easily perform a SELECT with the following bit of code:

	tx.executeSql('SELECT column1, column2 FROM foo',[], resultsFunction);


The second parameter is a simile array to be used if you need to pass in some value for the where clause. You have to specify am empty array even you don’t use it in order to be able to specify a callback function to handle the return result. To iterate through the result set, you perform a simple loop

Here is the other version:

	tx.executeSql('SELECT column1, column2 FROM foo WHERE column2 > ?',[3], function (tx, resultset)
	var res = resultset.rows.length;
	for(var i = 0; i<= res-1;i++)



Web Storage

Web Storage is a simplier form of offline storage, although it has its limits. Web Storage takes the form of a key, value pair and can hold up to 5 mb of data. This is an enhanced version of the cookie. The value can also contain a json or xml data. There are two types of HTML 5 Web Storage types: sessionStorage and localStorage.

The sessionStorage is great when you need temporary storage for multiple transactions from different windows on the same computer from the same origin.

To use the sessionStorage from HTML5 to set a value:

function foo(key, val)

To retrieve a sessionStorage value:

function getValue()
	var object = sessionStorage.getItem(key);


The second Web Storage form is the localStorage. As the name suggests, it provides a means to store data on a computer’s file system and last beyond the current session(s). The User agent can expire that data in the HTML5 local storage on demand or through some scheduled maintenance routine.

To set a value in the localStorage object:

function setAValue(key, value)
	window.localStorage.setItem(key, value);

To retrieve a value from the HTML5 localStorage:

function getAValue()
	var somevalue = window.localStorage.getItem(key);

To clear the localStorage:

function wipeOut()

To remove an item in particular from the localStorage:

function removeItem(key)

Both forms of the Web Storage inherit from the Storage interface and as such both implement the same methods. In addition to these methods, you also have the storage event.

Indexed Database (IndexedDB)

The last form of the HTML5 storage options is the Indexed Database option. The Indexed database object stores values as key, value items like the Web Storage in addition to having a builtin index. Records can be retrieved by key or index number and queries can be performed on the data. The Indexed Database can be implemented using the B-tree structure.

An origin (or source) may have several databases, which in turn, can have multiple data stores. Additionally, each database must have a name. Also the HTML5 IndexedDB is a transactional database.

To date, the IndexedDB is only partially implemented with Google Chrome and Firefox. Internet Explorer is in development and should be released with IE 10 so it might take another year or so to be able to use this technology. There is no word from Opera about their plans for the indexedDB.

Also at the time of writing, Google and Mozilla are implementing the indexeddb with a prefix: for Google (Webkit), it is webkitIndexedDB and for Firefox it is moz_indexedDB. So if you are creating an offline app that will target all major browsers then you will need to check the user_agent for the correct implementation.

As an example to create an Indexed database:

if('moz_indexedDB' in window)
	window.indexedDB = window.moz_indexedDB;

}else if("webkitIndexedDB" in window)
window.indexedDB = window.webkitIndexedDB ;

	//browser is not supported

Next you would need to open the database:

var database;
var req =
	'Database description'

The result of open is not an open database, rather it is a handle to the event which you capture and process:

req.onsuccess = function ( event ) 
	//do something like return a reference to the opened database for later use
	database = event.result;
req.onerror   = function ( event ) 
	//handle the error
	alert('Unable to open the database!');

Next before you can create object stores (rather than tables), you will need to set the version. This can be anything you want:

req = database.setVersion('1');
req.onsuccess = function(evt) {};
req.onerror  = function ( evt) {};

Now you can create an object store, add a key column and either set it to true to add a unique constraint or false,

var dbStore = database.createObjectStore(âaccountsâ, âidâ, true);

then you can create your indexes (or columns?)

dbStore = database.createIndex('tel', true);

dbStore = database.createIndex('accountName', false);

dbStore = database.createIndex('address', false);


Once you database is set up, you will need to add transactions and also query that data, here are some examples on accomplishing this.

var tx = database.transaction(['accounts'], IDBTransaction.READ_WRITE);
dbStore = tx.objectStore('accounts');

Create a write request:

var write = dbStore.add({'tel' : '555-555-0000', 'accountName' : 'MyCompany', 'address' : '123 somewhere'});

Handle the write events and errors:

write.onComplete = function(e) {};
write.onerror = function(e) {};

If you need to read from the object store:

var request = dbStore.get('555-555-0000');

Finally to remove a record:

var request = dbStore.delete('555-555-0000');

The event handlers are the same are previously described.

As I mentioned the indexedDB is at its earliest implementations and the proposed draft and final implementation by each major vendor is months if a year or so away depending on how fast their individual development schedules and roadmaps are implemented. However once one vendor implements a feature, you can be sure the others will follow in order to remain competitve in this rapidly evolving landscape.

This wraps up the HTML5 offline storage features that is and will continue to offer some very interesting options for developers for year to come.


    0 of 8192 characters used
    Post Comment

    No comments yet.