Google News
logo
JavaScript IndexedDB - Interview Questions
How do you open a database in IndexedDB?
In IndexedDB, opening a database involves a few steps. Below is a basic example of how to open a database:
// Step 1: Open or create a database
var request = indexedDB.open("myDatabase", 1);

// Step 2: Handle the database events
request.onerror = function(event) {
    // Handle errors
    console.log("Error opening database");
};

request.onsuccess = function(event) {
    // Get reference to the opened database
    var db = event.target.result;
    console.log("Database opened successfully");
    
    // Further database operations can be performed here
};

// Step 3: Define the database structure in case of upgrade
request.onupgradeneeded = function(event) {
    // Get reference to the opened database
    var db = event.target.result;

    // Create an object store (table) to store data
    var objectStore = db.createObjectStore("myObjectStore", { keyPath: "id" });

    // Define indexes if needed
    objectStore.createIndex("name", "name", { unique: false });
    objectStore.createIndex("email", "email", { unique: true });
};?
Explanation :

* We use indexedDB.open() method to open or create a database. It takes two parameters: the name of the database and the version number. If the database doesn't exist, it will be created. If it does exist, the version number will determine whether an upgrade is needed.

* We attach event handlers to handle different events during the database opening process:
* request.onerror : This event is triggered if there is an error opening the database.
* request.onsuccess : This event is triggered when the database is successfully opened. We can get a reference to the opened database using event.target.result.
* request.onupgradeneeded : This event is triggered when the database needs to be upgraded (e.g., when the version number provided during the opening operation is greater than the existing version). Here, we can define the database structure, such as creating object stores and indexes.

* Inside the onupgradeneeded event handler, we define the structure of the database by creating object stores (similar to tables in relational databases) using db.createObjectStore(). We can also create indexes on object stores using objectStore.createIndex() if needed.

* Once the database is successfully opened (onsuccess event), further database operations can be performed within the callback function.
Advertisement