Opening a Database Connection
You'll learn how to initiate a connection to an IndexedDB database and prepare it for use.
When you want to work with IndexedDB, the first step is always opening a database connection. Think of it like unlocking a vault—you need to establish access before you can store or retrieve anything inside.
The indexedDB.open() Method
To open a database, you use indexedDB.open(), which takes two parameters:
let request = indexedDB.open('MyDatabase', 1);
The first parameter is the database name (like naming your vault), and the second is the version number (starting at 1). The version number is crucial—it's how IndexedDB knows when you're making structural changes.
Handling the Request Events
indexedDB.open() returns a request object that fires different events:
let request = indexedDB.open('MyDatabase', 1);
request.onsuccess = function(event) {
let db = event.target.result;
console.log('Database opened successfully!');
};
request.onerror = function(event) {
console.error('Error opening database:', event.target.error);
};
request.onupgradeneeded = function(event) {
let db = event.target.result;
console.log('Database upgrade needed');
// This is where you create object stores (covered later)
};
The onupgradeneeded event fires when you open a database for the first time or when you increase the version number. This is your opportunity to set up or modify the database structure.
The onsuccess event fires when the connection is ready to use, giving you access to the database through event.target.result.
The onerror event handles any problems during the opening process.
Key Takeaway: Use indexedDB.open(name, version) to establish a database connection, and handle onsuccess, onerror, and onupgradeneeded events to manage the connection lifecycle and version upgrades.