Site icon Sibeesh Passion

Introduction to IndexedDB

[toc]

Introduction

In this post, we will see some information about IndexedDB. As the name implies, IndexedDB is a database in which we can do all kind of operations we do in a normal database. This IndexedDB has been introduced with the HTML5 . This allows a user to store a large amount of data in user’s browser. It has been proved that IndexedDB is more powerful and efficient than other storage mechanisms like local storage and session storage. Basically, IndexedDB is an API which helps the developers to do some database operations in client side, like creating a database, open the transaction, creating tables, inserting values to tables, deleting values, reading the data. If you need any other way to save some data in client side, you can use storage mechanisms introduced in HTML5. Now we will look some of the operations a developer can do with IndexedDB. I hope you will like this.

Background

Before introducing IndexedDB, developers were familiar with Web SQL. If you need to know more about Web SQL you can see here: Web SQL Introduction.

Why to use IndexedDB instead Web SQL?

W3C has been announced that use of Web SQL is obsolete and deprecated, hence it is not recommended using Web SQL in your applications. Most of the modern web browsers like Mozilla does not support the use of Web SQL, this is also a great limitation of Web SQL.

Now we have an alternative to Web SQL, IndexedDB which more efficient and faster than Web SQL. Below are some of the main advantages of IndexedDB.

  • It stores the data as Key-Pair values
  • It is Asynchronous
  • It is non relational
  • Can access the data from the same domain
  • Using the code

    As you all know, the first step to work with a database is just creating it.

    Create/Open IndexedDB Database

    It is always better to check whether your browser is supporting IndexedDB or not. To check that you can use the following syntax.

    [js]
    <script type="text/javascript">
    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    //check whether the database is created or not.
    if (!window.indexedDB) {
    alert("Oops, Does not support IndexedDB");
    }
    </script>
    [/js]

    So if your browser is supporting IndexedDB, you are ready to go!. Cool!. Now we can create a database.

    [js]
    //check whether the database is created or not.
    if (!window.indexedDB) {
    alert("Oops, Does not support IndexedDB");
    } else {
    //Create database
    var dbName = ‘myDB’;// Database name
    var dbVersion = 2;// Database version
    var crDB = window.indexedDB.open(dbName, dbVersion);
    }
    [/js]

    Here the first parameter is the database name and the second one is the version of your database. A version represents your database’s current schema. If everything goes well, you can see your database in your browser’s resources as follows.

    IndexedDB Creation

    When you create a database there some certain events are getting fired, they are

    onupgradeneeded

    [js]
    crDB.onupgradeneeded = function (event) {
    alert("That’s cool, we are upgrading");
    db = event.target.result;
    var objectStore = db.createObjectStore("UserName", { keyPath: "UserID" });
    };
    [/js]

    This event gets fired when you try upgrading your database. Here we are creating an object store with name ‘UserName’ and index key ‘UserID’. Below is the output you get when the onupgradeneeded is fired.

    IndexedDB onupgradeneeded Alert

    IndexedDB onupgradeneeded Output

    onsuccess

    [js]
    crDB.onsuccess = function (event) {
    alert("Awesome, You have successfully Opened a Databse!");
    db = event.target.result;
    }
    [/js]

    If there are no errors, you will get an alert as follows.

    IndexedDB OnSuccess Alert

    onerror

    [js]
    crDB.onerror = function (event) {
    alert("Oops, There is error!", event);
    }
    [/js]

    Here crDB is our database instance. Once this is done, we can start using the transaction as we use in SQL.

    Creating transaction

    To create a transaction we can use the following syntax. We can use transaction method from our database instance.

    [js]
    //Creating transaction
    var myTran = db.transaction(["UserName"], "readwrite");

    myTran.oncomplete = function (e) {
    alert("Awesome, Transaction is successfully created!");
    };

    myTran.onerror = function (e) {
    alert("Oops, There is error!", e.message);
    };
    [/js]

    Here db is our database instance. And myTran is our transaction object which we are going to use for our upcoming operations. We are creating a transaction with read-write permission, that is why we have given a property as ‘readwrite’ while creating a transaction. Why we use transaction is, as you all know transaction can be rollbacked. For example, if any of the operation throws an error, the transaction will be rollbacked so there won’t be any kind of mismatching data happening. And of course, we can easily manage error logs with the help of transaction. Shall we write queries needed for our operations?

    Adding the data

    Once our transaction is ready we can insert some data into our object in the transaction on success event, which we have called inside of database onsuccess event. Please check the below code.

    [js]
    crDB.onsuccess = function (event) {
    alert("Awesome, You have successfully Opened a Databse!");
    db = event.target.result;

    //Creating transaction
    var myTran = db.transaction(["UserName"], "readwrite");

    myTran.oncomplete = function (e) {
    alert("Awesome, Transaction is successfully created!");
    };

    myTran.onsuccess = function (e) {
    alert("Awesome, Transaction is successfully created!");
    //Adding the data
    var myObj = myTran.objectStore("UserName");

    var myNames = ["Sibi", "Aji", "Ansu", "Shantu", "Aghil"];//Array with names

    for (var i = 0; i < 5; i++) {//Adding 5 objects
    myObj.add({ UserID: ‘SBKL0’ + i, Name: myNames[i] });
    }
    };

    myTran.onerror = function (e) {
    alert("Oops, There is error!", e.message);
    };

    }
    [/js]

    Here myNames is the array in which we have few names and we are using a loop to insert few data to the object. Now you can see that your data have been added to the object in your browser’s resources.

    IndexedDB Adding Data To Objects

    We have successfully added data. Right? Now we will see how we can remove the data we just added 🙂

    Removing the data

    If there is adding, there should be deleting :). You can delete an object from object store as follows.

    [js]
    setTimeout(function () {
    db.transaction(["UserName"], "readwrite").objectStore("UserName").delete(‘SBKL00’);
    }, 10000);
    [/js]

    So you can rewrite the on success event of transaction s follows.

    [js]
    myTran.onsuccess = function (e) {
    alert("Awesome, Transaction is successfully created!");
    //Adding the data
    var myObj = myTran.objectStore("UserName");

    var myNames = ["Sibi", "Aji", "Ansu", "Shantu", "Aghil"];//Array with names

    for (var i = 0; i < 5; i++) {//Adding 5 objects
    myObj.add({ UserID: ‘SBKL0’ + i, Name: myNames[i] });
    }

    setTimeout(function () {
    db.transaction(["UserName"], "readwrite").objectStore("UserName").delete(‘SBKL00’);
    }, 10000);
    };
    [/js]

    It can give you an output as follows.

    IndexedDB Deleting Data From Objects

    Now we will see how we can access a particular data from the object store.

    Access the data with key

    To access a particular data, we will add a button and in the button click event, we will fetch the details needed as a request.

    [html]
    <input id="btnGet" type="button" value="Get Name" />
    [/html]

    Click event is as follows.

    [js]
    $(function () {
    $(‘#btnGet’).click(function () {
    var get = db.transaction(["UserName"], "readwrite").objectStore("UserName").get(‘SBKL01’);
    get.onsuccess = function (event) {
    alert("The name you have requested is : " + get.result.Name);
    };

    });
    });
    [/js]

    You can get the alert as follows, if your run your code.

    IndexedDB Get The Data With Key

    Now we will see how we can update data with the Get method.

    Updating the data

    To update the data we will have a button and in the button click we will fire the needed code.

    [html]
    <input id="btnUpdate" type="button" value="Update Name" />
    [/html]

    And click event is as follows.

    [js]
    $(‘#btnUpdate’).click(function () {
    var updObject = db.transaction(["UserName"], "readwrite").objectStore("UserName");
    var upd=updObject.get(‘SBKL03’);
    upd.onsuccess = function (event) {
    upd.result.Name = ‘New Name’;
    updObject.put(upd.result);
    };

    });
    [/js]

    Here we are getting an element using the get method, and we are updating the value in the result, once it is done, we will assign that new result to the object store using put method.

    It will give you an output as follows.

    IndexedDB Update The Data With Key

    Another interesting thing is, we can use cursors also as we use in SQL if we need to loop through some data. Here I will show you how we can do that.

    Using Cursor

    Create a button and write few code as follows.

    [html]
    <input id="btnShow" type="button" value="Show the data" />
    [/html]

    Then we will create an HTML table.

    [html]
    <div id="myTab">
    <table id="show">
    <thead>
    <th>User ID </th>
    <th>Name</th>
    </thead>
    <tbody></tbody>
    </table>
    </div>
    [/html]

    Now we can write the cursor as follows.

    [js]
    $(‘#btnShow’).click(function () {
    var curObject = db.transaction(["UserName"], "readwrite").objectStore("UserName");
    curObject.openCursor().onsuccess = function (event) { //Opening the cursor
    var cur = event.target.result;
    if (cur) {// Checks for the cursor
    $(‘#show’).append(‘<tr><td>’ + cur.key + ‘</td><td>’ + cur.value.Name + ‘</td></tr>’);
    cur.continue();
    }
    };
    $(‘#myTab’).show();
    });
    [/js]

    Here we are creating a cursor using the function openCursor() and in the onsuccess event we are looping through the cursor. You can always give some styles to your table.

    [css]
    <style>
    table, tr, td, th {
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    margin: 10px;
    }
    </style>
    [/css]

    That is all 🙂 Now when you click the show button, you can see the data in a table format as follows.

    IndexedDB Using Cursor

    Complete code

    [html]
    <!DOCTYPE html>
    <html>
    <head>
    <title>Introduction to IndexedDB</title>
    <script src="Scripts/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    var dbName = ‘myDB’;// Database name
    var dbVersion = 2;// Database version
    var crDB;
    var db;
    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    //check whether the database is created or not.
    if (!window.indexedDB) {
    alert("Oops, Does not support IndexedDB");
    } else {
    //Create database
    crDB = window.indexedDB.open(dbName, dbVersion);
    var db;
    crDB.onerror = function (event) {
    alert("Oops, There is error!", event);
    }
    crDB.onupgradeneeded = function (event) {
    alert("That’s cool, we are upgrading");
    db = event.target.result;
    var objectStore = db.createObjectStore("UserName", { keyPath: "UserID" });
    };
    crDB.onsuccess = function (event) {
    alert("Awesome, You have successfully Opened a Databse!");
    db = event.target.result;

    //Creating transaction
    var myTran = db.transaction(["UserName"], "readwrite");

    myTran.oncomplete = function (e) {
    alert("Awesome, Transaction is successfully created!");
    };

    myTran.onsuccess = function (e) {
    alert("Awesome, Transaction is successfully created!");
    //Adding the data
    var myObj = myTran.objectStore("UserName");

    var myNames = ["Sibi", "Aji", "Ansu", "Shantu", "Aghil"];//Array with names

    for (var i = 0; i < 5; i++) {//Adding 5 objects
    myObj.add({ UserID: ‘SBKL0’ + i, Name: myNames[i] });
    }

    setTimeout(function () {
    db.transaction(["UserName"], "readwrite").objectStore("UserName").delete(‘SBKL00’);
    }, 10000);
    };

    myTran.onerror = function (e) {
    alert("Oops, There is error!", e.message);
    };

    }
    }
    $(function () {
    $(‘#myTab’).hide();
    $(‘#btnGet’).click(function () {
    var get = db.transaction(["UserName"], "readwrite").objectStore("UserName").get(‘SBKL01’);
    get.onsuccess = function (event) {
    alert("The name you have requested is : " + get.result.Name);
    };

    });
    $(‘#btnUpdate’).click(function () {
    var updObject = db.transaction(["UserName"], "readwrite").objectStore("UserName");
    var upd = updObject.get(‘SBKL03’);
    upd.onsuccess = function (event) {
    upd.result.Name = ‘New Name’;
    updObject.put(upd.result);
    };

    });
    $(‘#btnShow’).click(function () {
    var curObject = db.transaction(["UserName"], "readwrite").objectStore("UserName");
    curObject.openCursor().onsuccess = function (event) { //Opening the cursor
    var cur = event.target.result;
    if (cur) {// Checks for the cursor
    $(‘#show’).append(‘<tr><td>’ + cur.key + ‘</td><td>’ + cur.value.Name + ‘</td></tr>’);
    cur.continue();
    }
    };
    $(‘#myTab’).show();
    });
    });
    </script>
    <style>
    table, tr, td, th {
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 10px;
    margin: 10px;
    }
    </style>
    </head>
    <body>
    <input id="btnGet" type="button" value="Get Name" />
    <input id="btnUpdate" type="button" value="Update Name" />
    <input id="btnShow" type="button" value="Show the data" />
    <div id="myTab">
    <table id="show">
    <thead>
    <th>User ID </th>
    <th>Name</th>
    </thead>
    <tbody></tbody>
    </table>
    </div>
    </body>
    </html>
    [/html]

    That is all. We did it. Have a happy coding.

    Conclusion

    Did I miss anything that you may think which is needed? Did you try Web SQL yet? Have you ever wanted to do this requirement? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.

    Your turn. What do you think?

    A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.

    Kindest Regards
    Sibeesh Venu

    Exit mobile version