Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

HTML5Storage In HTML5
Home›HTML5›Introduction to IndexedDB

Introduction to IndexedDB

By SibeeshVenu
February 10, 2016
1359
0
Share:
IndexedDB Creation

[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

    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 Alert

    IndexedDB onupgradeneeded Output

    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

    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

    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

    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

    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

    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

    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

    TagsIndexedDBIndexedDB And Web SQLopenCursor()Storage in HTML5
    Previous Article

    Solutions for the error “the server responded ...

    Next Article

    Web API With Angular JS

    0
    Shares
    • 0
    • +
    • 0
    • 0
    • 0

    SibeeshVenu

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

    Related articles More from author

    • HTML5Storage In HTML5

      Remove Filtered sessionStorage And localStorage

      August 11, 2015
      By SibeeshVenu
    • HTML5

      Basic Difference Between Local Storage and Session Storage in HTML 5

      March 29, 2015
      By SibeeshVenu
    • CodeProjectHTML5

      Working With Client Side Local Storage

      August 3, 2015
      By SibeeshVenu
    • Create Custom Colour Palette
      HTML5JQuery

      Creating Custom Color Palette Using JQuery, HTML5, CSS

      March 29, 2015
      By SibeeshVenu
    • Create Tooltip Without Any Plugins
      CodeProjectHTMLHTML5JQuery

      Create Tooltip Without Any Plugins

      September 29, 2015
      By SibeeshVenu
    • HTML5

      Client Side Chart Widget in HTML5: Part 5 (Polar Area Chart)

      May 29, 2015
      By SibeeshVenu
    0

    My book

    Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

    YouTube

    MICROSOFT MVP (2016-2022)

    profile for Sibeesh Venu - Microsoft MVP

    Recent Posts

    • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
    • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
    • Easily move data from one COSMOS DB to another
    • .NET 8 New and Efficient Way to Check IP is in Given IP Range
    • Async Client IP safelist for Dot NET
    • Post Messages to Microsoft Teams Using Python
    • Get Azure Blob Storage Blob Metadata Using PowerShell
    • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
    • Integrate Azure App Insights in 1 Minute to .Net6 Application
    • Azure DevOps Service Connection with Multiple Azure Resource Group

    Tags

    Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
    • .NET
    • Achievements
    • ADO.NET
    • Android
    • Angular
    • Arduino
    • Article Of The Day
    • ASP.NET
    • Asp.Net Core
    • Automobile
    • Awards
    • Azure
    • Azure CDN
    • azure devops
    • Blockchain
    • Blog
    • Browser
    • C-Sharp Corner
    • C#
    • Career Advice
    • Code Snippets
    • CodeProject
    • Cognitive Services
    • Cosmos DB
    • CSS
    • CSS3
    • Data Factory
    • Database
    • Docker
    • Drawings
    • Drill Down Chart
    • English
    • Excel Programming
    • Exporting
    • Facebook
    • Fun
    • Gadgets
    • GitHub
    • GoPro
    • High Map
    • HighChart
    • How to
    • HTML
    • HTML5
    • Ignite UI
    • IIS
    • Interview
    • IoT
    • JavaScript
    • JQuery
    • jQuery UI
    • JQWidgets
    • JQX Grid
    • Json
    • Knockout JS
    • Linux
    • Machine Learning
    • Malayalam
    • Malayalam Poems
    • MDX Query
    • Microsoft
    • Microsoft ADOMD
    • Microsoft MVP
    • Microsoft Office
    • Microsoft Technologies
    • Microsoft Windows
    • Microsoft Windows Server
    • Mobile
    • MongoDB
    • Monthly Winners
    • MVC
    • MVC Grid
    • MySQL
    • News
    • Node JS
    • npm
    • Number Conversions
    • October 2015
    • Office 365
    • Office Development
    • One Plus
    • Outlook
    • Page
    • PHP
    • Poems
    • PowerShell
    • Products
    • Q&A
    • Raspberry PI
    • React
    • SEO
    • SharePoint
    • Skype
    • Social Media
    • Software
    • Spire.Doc
    • Spire.PDF
    • Spire.XLS
    • SQL
    • SQL Server
    • SSAS
    • SSMS
    • Storage In HTML5
    • Stories
    • Third Party Software Apps
    • Tips
    • Tools
    • Translator Text
    • Uncategorized
    • Unit Testing
    • UWP
    • VB.Net
    • Videos
    • Virtual Machine
    • Visual Studio
    • Visual Studio 2017
    • Wamp Server
    • Web API
    • Web Platform Installer
    • Webinars
    • WebMatrix
    • Windows 10
    • Windows 7
    • Windows 8.1
    • Wordpress
    • Writing

    ABOUT ME

    I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

    Contact Me

    • info@sibeeshpassion.com

    Pages

    • About
    • Search
    • Privacy Policy
    • About
    • Search
    • Privacy Policy
    © Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
    Go to mobile version