What is IndexedDB?
The IndexedDb (Indexed database) is a Javascript application programming interface provided by web browsers for managing NoSQL database of JSON objects. It is a standard maintained by the World Wide Web Consortium. As an alternative to localStorage, IndexedDB can provide more storage capacity and can store more data as compared to local storage.
When to use IndexedDB?
IndexedDB is used in different scenarios and depends on the developer's needs. Mostly it is used to store data that is not likely to be changed again and again or meta data is stored in IndexedDB. For example you can store some data of a logged in user in Indexed db as he logged in and in an application you can use it according to your need. One more use is to store permission details of loggedin user in indexedDB.
Creating IndexedDB
Follow the following steps to create an IndexedDB,
First of all we will create a simple html file that will have a button to create a new IndexedDB. For that, create a HTML file and add following code,
- <!DOCTYPE html>
- <html>
-
- <body>
- <button id="btnCreateStore" onclick="initDB()">Initialize Database</button>
- <p id="result"></p>
- <div id="UsersContainer" style="display: none;">
- <button id="btnShowUsers" onclick="showUsers()">Show Users</button>
- <p>
- <input type="text" id="txtName">
- <input type="text" id="txtEmail">
- <input type="text" id="txtCountry">
- <button type="button" onclick="addUser()">Add</button>
- </p>
- <div id="UsersTable">
-
- </div>
- </div>
- </body>
-
- </html>
Next step is to create and initialize IndexedDB when you click on the Initialize Database button. For that, create a script tag in the html file and add the following function,
- var friends_Data = [
- { EmployeeName: "Jamil Moughal", EmployeeEmail: "[email protected]", Country: "Pakistan" },
- { EmployeeName: "Diviya", EmployeeEmail: "[email protected]", Country: "India" },
- { EmployeeName: "Ali Khan", EmployeeEmail: "[email protected]", Country: "Egypt" },
- { EmployeeName: "John Charles", EmployeeEmail: "[email protected]", Country: "United States" },
- { EmployeeName: "Steve", EmployeeEmail: "[email protected]", Country: "Germany" },
- ];
-
- function initDB() {
- var Database_Name = "UsersDB";
- var DB_Version = "1.0";
- var dbObj;
- var request = indexedDB.open(Database_Name, DB_Version)
- request.onsuccess = function (e) {
- document.getElementById("result").innerHTML = "Database Opened :)";
- dbObj = request.result;
- document.getElementById('UsersContainer').style.display = 'block';
- }
- request.onerror = function (e) {
- console.log("Error:" + e.target.errorCode)
- document.getElementById("result").innerHTML = "Error! The Database connection not opened. Please See The Log";
- }
- request.onupgradeneeded = function (e) {
-
- var objectStore = e.currentTarget.result.createObjectStore("MyObjectStore", { keyPath: "id", autoIncrement: true });
-
-
- objectStore.createIndex("EmployeeName", "EmployeeName", { unique: false });
- objectStore.createIndex("EmployeeEmail", "EmployeeEmail", { unique: true });
- objectStore.createIndex("Country", "Country", { unique: false });
-
-
- for (i in friends_Data) {
- objectStore.add(friends_Data[i]);
- }
- };
- }
After this, refresh your html file and click on Initialize Database button, then open your browser console and click on Application window. You will see the IndexedDB, in the database above records will be present. It will look as follows,
Database is created in IndexedDB storage named as UsersDB. It also has a Store named as MyObjectStore which have all the records that we have added. Now we will get all records from the IndexedDB storage. We will do this when clicking on Show Users button. Add the following function in your code.
- function showUsers() {
- var Database_Name = "UsersDB";
- var DB_Version = "1.0";
-
- var request = window.indexedDB.open(Database_Name, DB_Version)
- var db;
- request.onsuccess = function (e) {
- db = e.target.result;
- var transaction = db.transaction("MyObjectStore", "readwrite");
- var objectStore = transaction.objectStore("MyObjectStore");
-
- var emp_name = "";
-
- var add_request = objectStore.getAll()
- add_request.onsuccess = function (e) {
- var list = e.target.result;
- var _html = "";
- if (list != undefined && list.length > 0) {
- for (let index = 0; index < list.length; index++) {
- _html += "<p>";
- _html += 'EmployeeName: <strong>' + list[index].EmployeeName + '</strong>Email:<strong>' + list[index].EmployeeEmail + '</strong>Country:<strong>' + list[index].Country + '</strong>';
- _html += '<button type="button" onclick="deleteUser(' + list[index].id + ')" style="background: red; color: white;">Delete</button>';
- _html += '</p>';
- }
- }
- document.getElementById('UsersTable').innerHTML = _html;
-
- };
- transaction.oncomplete = function (e) {
-
- };
- transaction.onabort = function (e) {
-
- };
- transaction.onerrort = function (e) {
-
- };
- }
- }
After adding code, save and refresh the file and click on Show Users button. Your screen will look as,
We have successfully created a new Database in IndexedDB and have added some dummy data for testing. Now we will add data by user action. When user will add data in textboxes and press the Add button, data from textboxes should be added in database. For this add the following function in your code,
- function addUser() {
- var Database_Name = "UsersDB";
- var DB_Version = "1.0";
-
- var request = window.indexedDB.open(Database_Name, DB_Version)
- var db;
- request.onsuccess = function (e) {
- db = e.target.result;
- var transaction = db.transaction("MyObjectStore", "readwrite");
- var objectStore = transaction.objectStore("MyObjectStore");
- var add_request = objectStore.add({ EmployeeName: 'Good Boy', EmployeeEmail: "[email protected]", Country: "Austria" });
- add_request.onsuccess = function (e) {
-
- };
- transaction.oncomplete = function (e) {
-
- };
- transaction.onabort = function (e) {
-
- };
- transaction.onerrort = function (e) {
-
- };
- }
- }
When you will click on Add button a new entry will be added in your IndexedDB storage. Now we will learn how we can delete some specific record in the database. For this, add the following function in your code.
- function deleteUser(Id) {
- var Database_Name = "UsersDB";
- var DB_Version = "1.0";
-
- var request = window.indexedDB.open(Database_Name, DB_Version)
- var db;
- request.onsuccess = function (e) {
- db = e.target.result;
- var transaction = db.transaction("MyObjectStore", "readwrite");
- var objectStore = transaction.objectStore("MyObjectStore");
-
-
- var request = db.transaction("MyObjectStore", "readwrite")
- .objectStore("MyObjectStore")
- .delete(Id);
- request.onsuccess = function (event) {
-
- };
-
- }
- }
Now we are done with our things. We have learned how IndexedDb is created, how data is retrieved and how records can be removed.
Thank you.
Happy Coding