2

I have created indexedDB database that contain multiple table and data. now i want to reopen existing indexedDB database and want to read data from specific tables.please help me

kashyap
  • 31
  • 3

1 Answers1

3

IDB version number

In IndexedDB, typically database is opened (opened for the first time or re-opened for modification) using window.indexedDB.open(DB_NAME, DB_VERSION);

Here, DB_VERSION is the version number of database that determines whether database will be opened for creation or modification or read.

Further readings:

How IDB version number works

  • For the first time when you call open, you will typically call with version number as 1, which will fire onupgradeneeded event handler (this event handler can be used to "create" database schema) and onsuccess event handler (this event handler will be used to save database handler) in order, and then you can access the database using the database handler.
  • Next time when you may call open with a upgraded/higher version number then again onupgradeneeded event handler (this event handler can be used to "create" database schema) and onsuccess event handler (this event handler will be used to save database handler) will be fired in order.
  • Next time when you may call open with same version number (reopen for read) then again only onsuccess event handler (this event handler will be used to save database handler) will be fired in order.

Please note

  • onupgradeneeded event handler is used to create or modify database schema.
  • onsuccess event handler is used to get the database handler which will be used to access database.
  • IMPORTANT: Typically you should not call open again and again (until you wish to modify the database schema), but for the first time when you call then you should save the database handler using onsuccess event handler and then access the database using that database handler.

Example code for understanding

Use below once, and see the alerts, then execute again (without clear cache on browser so that same database still exists) and then see the alert.

    var request = window.indexedDB.open("SO", 1);

    request.onblocked = function(event) {
        alert("Error, cannot open database. Error message: Database in blocked state. " +
                "Please close all open windows, clear browser cache and use a fresh window.");
    };

    //Callback for error upon DB open 
    request.onerror = function(event) {
      alert('Error, cannot open database/Erreur, ne peut pas ouvrir la base de données');
    };

    //Callback for success upon DB open
    request.onsuccess = function(event) {
        alert('onsuccess. Save your database handler, for example something, DB_HANDLER = event.target.result;');
    };

    //Callback for onupgradeneeded upon DB open
    request.onupgradeneeded = function(event) {
        alert('onupgradeneeded. Create/modify the database schema');
    };
hagrawal7777
  • 14,103
  • 5
  • 40
  • 70