ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Web SQL


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(http://www.w3.org/TR/webdatabase/) by the w3.org 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 w3.org 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:

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

}
);

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

db.transaction(function(tx)
{
	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:

*/
db.transaction(function(tx)
{
	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:

db.transaction(function(tx)
{
	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++)
	{
		alert(res.rows.item(i).text);


}
};

}
);

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)
{
	sessionStorage.setItem(key,valu);
}

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()
{
	window.localStorage.clear();
}

To remove an item in particular from the localStorage:

function removeItem(key)
{
	window.localStorage.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 ;

}else
{
	//browser is not supported
}

Next you would need to open the database:

var database;
var req = window.indexedDB.open(
	'databaseName',
	'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.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)