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 namedMyDatabase
with version1
.onupgradeneeded
: This event is triggered if the database is newly created or its version is upgraded. We create an object store (Users
) withid
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
andsessionStorage
. - Creating a database involves opening a connection and defining object stores.
Try Your Hand
- Modify the code to add another object store named
Products
. - Try catching errors and logging them properly.
Next, we'll learn how to store and retrieve data in IndexedDB.