How to Store, Retrieve & Delete data from HTML5 IndexedDB?

World is running under Client Server architecture. In real-time Customer interacts to Server through Clients. Server stores data. Depending upon the level of authentication and type of request Server provides data to Clients. As a common practice in this response request mechanism generally we use Database to store large amount of data. Which resides in Server. During http requests if the page contains data from the Database then it takes time to load. Which directly affects performance. How it is if we can operate large amount of data in Client machine? I can say definitely it will improve the performance.

IndexedDB is a new feature introduced in the 5th revision of HTML. Using IndexedDB we can store large amount of data to the Client Browser. Compare to a Cookie IndexedDB works faster and stores bigger. IndexedDB stores data in KEY & VALUE pair. The term has derived from Database. That’s why by hearing the term “IndexedDB” many of us guess SQL. No it is not like SQL. IndexedDB doesn’t support any kind of SQL query. IndexedDB runs under Single domain only.

Getting Started with HTML5 IndexedDB

To implement IndexedDB in a HTML5 page initially you required to declare the following js scripts.

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
 
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
 
if (!window.indexedDB) {
window.alert("Update your browser. Older version is incompatible for IndexedDB.")
}

Prepare Data for IndexedDB

Before we jump to Create a Database first let us keep some data ready. In below I am presenting few records from my “Employee_Details” table. Keep mark the Data Structure I presented below is in JSON form.

const employeeDetails = [
{ emp_id: "01", name: "Raghav Sukla", dob: "01/06/1980", email_id: "raghav@gmail.com" },
{ emp_id: "02", name: "Hariharan Swain", dob: "13/11/1972", email_id: "hariharan@gmail.com" }
{ emp_id: "03", name: "Satyabrata Panda", dob: "22/06/1973", email_id: "satyabrata@gmail.com" }
];

Create an IndexedDB Database

Like we do in SQL or any DBMS here also we required to Create a Database. Look at the below Code here I created a Database. The method I used is “window.indexedDB.open(“<Your Database Name>”). Under Database I handing 3 events onerror for error handling, onsuccess for successful response and onupgradeneeded for adding record during up-gradation.

var mydb;
var request = window.indexedDB.open("demoDb", 1);
/* Handling Error */
request.onerror = function(event) {
console.log("Error Occurred.");
};
/* Executing after Success */
request.onsuccess = function(event) {
mydb = request.result;
console.log("success: "+ mydb);
};
/* While Updating */
request.onupgradeneeded = function(event) {
var mydb = event.target.result;
var objectStore = mydb.createObjectStore("empDetails", {keyPath: "emp_id"});
            
for (var i in employeeDetails) {
objectStore.add(employeeDetails[i]);
}
}

How to Store records to HTML5 IndexedDB?

Without records Database is meaningless. Let’s watch the example below.

function insertRecords() {
var request = mydb.transaction(["empDetails"], "readwrite")
.objectStore("empDetails")
.add({ emp_id: "04", name: "Vratika Viswakarma", dob: "02/08/1982", email_id: "vratika@gmail.com" });
request.onsuccess = function(event) {
alert("Vratika Viswakarma is added to your Database.");
};
request.onerror = function(event) {
alert("Getting Errors.");
}
}

While adding records I am maintaining the same sequence and key value pairs.

Function to Read Data from HTML5 IndexedDB

You must aware of the power of a SQL SELECT Statement. Like the same look at the below code how I am fetching records from IndexedDB. Here I used “emp_id” as the WHERE Condition.

function readRecords() {
var trans = mydb.transaction(["empDetails"]);
var objectStore = trans.objectStore("empDetails");
var request = objectStore.get("04");
/* On Error */        
request.onerror = function(event) {
alert("Unable to Retrieve Data.");
};
/* On Success */            
request.onsuccess = function(event) {
// Here you can Operate request.result Data!
if(request.result) {
alert("Name: " + request.result.name + ", DOB: " + request.result.dob + ", Email: " + request.result.email_id);
}
else {
alert("Vratika Viswakarma couldn't be found in your database!");
}
};
}

In below this an another way to fetch records sequentially. You can say this trick is similar to a SQL Cursor.

function readAllRecords() {
var objectStore = mydb.transaction("empDetails").objectStore("empDetails");
objectStore.openCursor().onsuccess = function(event) {
var indexeddb_cursor = event.target.result;
if (indexeddb_cursor) {
alert("Name for id " + indexeddb_cursor.key + " is " + indexeddb_cursor.value.name + ", DOB: " + indexeddb_cursor.value.dob + ", Email: " + indexeddb_cursor.value.email_id);
indexeddb_cursor.continue();
}
else {
alert("No more entries!");
}
};
}

How to Delete records from HTML5 IndexedDB?

Delete is a very Common Operation of DBMS. In the below example we are passing “emp_id” to Delete a record.

function deleteRecords() {
var request = mydb.transaction(["empDetails"], "readwrite")
.objectStore("empDetails")
.delete("04");
request.onsuccess = function(event) {
alert("Vratika Viswakarma record has been removed from Database.");
};
}