IndexedDB - Connection
IndexedDB: Database Connection
Section titled “IndexedDB: Database Connection”A database is a fundamental component for storing and retrieving structured data. To interact with the data in an IndexedDB database, we must first establish a connection. This chapter covers the essential operations of creating, opening, versioning, and deleting a database using modern JavaScript practices.
Opening a Database Connection
Section titled “Opening a Database Connection”In IndexedDB, you create a new database or open an existing one using the indexedDB.open() method. This method is asynchronous and returns an IDBOpenDBRequest object immediately. The actual result of the operation (success or failure) is delivered through events.
const request = indexedDB.open(databaseName, version);databaseName: A string representing the name of the database.version: An optional positive integer. This version number is crucial for managing database schema changes. If the specified version is greater than the database’s current version, aupgradeneededevent is triggered.
This operation does not immediately give you a database connection. Instead, you must listen for events on the returned request object.
Handling Connection Events
Section titled “Handling Connection Events”There are three key events to handle when opening a connection:
onsuccess: Fired when the connection is successfully established. The database connection object is available viaevent.target.result.onerror: Fired if an error occurs during the connection attempt (e.g., disk quota exceeded, security errors).onupgradeneeded: Fired only when theversionnumber provided toopen()is higher than the existing database’s version (or if the database doesn’t exist yet). This is the only place where you can create or delete object stores and indexes.
Example: Basic Connection and Schema Setup
Section titled “Example: Basic Connection and Schema Setup”Here is a modern, complete example of how to open a database and set up its schema. This code uses modern ES6 syntax (let, const, arrow functions) and logs messages to the browser’s console, which is a best practice for development.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>IndexedDB Connection</title></head><body> <h1>IndexedDB Connection Example</h1> <div id="status">Initializing...</div>
<script> const dbName = "MyNotesAppDB"; const dbVersion = 1; const statusDiv = document.getElementById('status');
// All modern browsers support indexedDB globally. if (!window.indexedDB) { statusDiv.textContent = "Your browser doesn't support a stable version of IndexedDB."; }
// Let's open our database const request = indexedDB.open(dbName, dbVersion);
request.onerror = (event) => { console.error(`Database error: ${event.target.error.message}`); statusDiv.textContent = 'Error opening database.'; };
request.onsuccess = (event) => { console.log('Database opened successfully.'); statusDiv.textContent = 'Database connection successful!'; // The db object is the connection to the database const db = event.target.result; // It's a good practice to close the connection when you're done db.close(); };
request.onupgradeneeded = (event) => { console.log('Database upgrade needed or database created.'); statusDiv.textContent = 'Setting up database schema...'; const db = event.target.result;
// Create an object store for our notes // This is like a table in a relational database const objectStore = db.createObjectStore("notes", { keyPath: "id", autoIncrement: true });
// Create an index to search notes by title. Indexes allow for fast searching. objectStore.createIndex("title", "title", { unique: false }); objectStore.createIndex("created_at", "created_at", { unique: false });
console.log('Object store and indexes created.'); }; </script></body></html>Verification in Browser DevTools
Section titled “Verification in Browser DevTools”You can verify the creation and structure of your database directly in your browser’s developer tools:
- Open the page in your browser.
- Right-click and select ‘Inspect’ or press F12 to open Developer Tools.
- Navigate to the ‘Application’ tab.
- In the left-hand menu, find ‘Storage’ and expand the ‘IndexedDB’ section.
- You will see your database, ‘MyNotesAppDB’. Expanding it will show the ‘notes’ object store and its indexes.
Deleting a Database
Section titled “Deleting a Database”To remove a database entirely, use the indexedDB.deleteDatabase() method. This is also an asynchronous operation.
const deleteRequest = indexedDB.deleteDatabase(dbName);A common issue is attempting to delete a database while it has open connections. You must close all connections to a database before the browser will delete it.
Example: Deleting a Database
Section titled “Example: Deleting a Database”// Ensure all connections to 'MyNotesAppDB' are closed before running this.const dbName = "MyNotesAppDB";const deleteRequest = indexedDB.deleteDatabase(dbName);
deleteRequest.onsuccess = () => { console.log(`Database '${dbName}' deleted successfully.`);};
deleteRequest.onerror = (event) => { console.error(`Error deleting database: ${event.target.error.message}`);};
// This event is fired if the deletion is blocked by an open connection.deleteRequest.onblocked = () => { console.warn('Database deletion blocked. Please close all open connections.');};Closing a Connection
Section titled “Closing a Connection”While browsers automatically manage connection lifecycles, it is a good practice to explicitly close a database connection when it’s no longer needed, especially before a deletion operation. You can call the close() method on the database object obtained from a successful connection.
request.onsuccess = (event) => { const db = event.target.result; // ... perform operations ... db.close();};