We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 58 - Creating an IndexedDB Database

IndexedDB is a low-level API for storing large amounts of structured data. Unlike localStorage and sessionStorage, IndexedDB allows you to store objects and query them efficiently.

Creating an IndexedDB Database

To create an IndexedDB database, you use the indexedDB.open method.

Example: Creating a Database

// Open (or create) a database named "MyDatabase" with version 1
let request = indexedDB.open("MyDatabase", 1);

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

    // Create an object store named "Users" with "id" as the primary key
    let objectStore = db.createObjectStore("Users", { keyPath: "id" });

    console.log("Database setup complete!");
};

request.onsuccess = function(event) {
    console.log("Database opened successfully!");
};

request.onerror = function(event) {
    console.log("Error opening database:", event.target.errorCode);
};

Explanation:

  • indexedDB.open("MyDatabase", 1): Opens or creates a database named MyDatabase with version 1.
  • onupgradeneeded: This event is triggered if the database is newly created or its version is upgraded. We create an object store (Users) with id as the primary key.
  • onsuccess: Fires when the database is successfully opened.
  • onerror: Fires if an error occurs.

Checking If a Database Exists

You can check if a database exists by trying to open it:

let checkRequest = indexedDB.open("MyDatabase");

checkRequest.onsuccess = function(event) {
    console.log("Database exists!");
};

checkRequest.onerror = function(event) {
    console.log("Database does not exist.");
};

Summary

  • IndexedDB is useful for storing structured data efficiently.
  • It provides asynchronous operations, unlike localStorage and sessionStorage.
  • Creating a database involves opening a connection and defining object stores.

Try Your Hand

  1. Modify the code to add another object store named Products.
  2. Try catching errors and logging them properly.

Next, we'll learn how to store and retrieve data in IndexedDB.