by @kodeazy

How to store data in browser using IndexDB part -II

Home » javascript » How to store data in browser using IndexDB part -II

To create or open an existing database we use

var request = indexedDB.open('firstDB',1);

Here request is a promise returned by indexedDB.open('firstDB',1); that resolved to object of database

Once the database is created to stores are required to add the data into the database

Store is similar to Tables or collections in MySql or MongoDB

To create Stores the syntax is

var ObjStore=db.ObjectStore('contacts');

In the above example db has the connection to the database

with the help of ObjStore you can peroform CRUD operations to the store in the database

var request = indexedDB.open("firstDB", 1);
request.onsuccess = function (e) {
  db = e.target.result;

  console.log(db);

  console.log("DB Opened!");
};

request.onerror = function (e) {
  console.log(e);
};

request.onupgradeneeded = function (e) {
  db = e.target.result;

  if (db.objectStoreNames.contains("co")) {
    db.deleteObjectStore("con");
  }
  var contactObjStore = db.createObjectStore("contacts");
};

Here if you are creating the database for the first time onupgradeneeded is called and the stores are created inside the onupgradeneeded and later onsuccess method is called

Here e.target.result holds the connection to the database

If you want to create a new store for your database then you have to create a new function with new version and then you have to add the name of store in onupgradeneeded method or else you can not create new store

Once the code is executed you can check the database and store in your browser by inspecting the browser and goint to the Application part

In part III we will be discussing on how to perform CRUD operations on IndexDB database