HTML5 Web IndexedDB Database
IndexedDB is a browser-based NoSQL database used to persistently store large amounts of structured data on the client side.
IndexedDB allows storing complex data objects (such as objects, arrays, files, etc.) via key-value pairs, and supports transactions, indexes, version control, and complex query operations.
IndexedDB is asynchronous and does not block the main thread, making it suitable for offline applications, caching, and other scenarios.
IndexedDB is very suitable for applications that need to store large amounts of structured data, especially Web applications that wish to support offline mode or handle complex queries.
IndexedDB Features
- Key-value pair storage: Data is stored in object stores in the form of key-value pairs.
- Transaction support: All data operations must be completed within a transaction to ensure data consistency and integrity.
- Asynchronous API: All operations are asynchronous and do not block the UI thread, using event callbacks or Promises to handle results.
- Version control: The database uses version numbers to manage the database schema (such as creating or modifying object stores).
- Indexes: Supports creating indexes on fields of data to speed up queries.
- Offline support: Data can be persistently stored and accessed even when the network is disconnected, making it very suitable for building offline Web applications.
IndexedDB Syntax
The IndexedDB syntax is described as follows:
var request = indexedDB.open('databaseName', version);
// Handle database upgrade
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an object store (table) and set the primary key
var objectStore = db.createObjectStore('storeName', { keyPath: 'id' });
// Create an index
objectStore.createIndex('fieldName', 'fieldName', { unique: false });
};
// Callback when database opens successfully
request.onsuccess = function(event) {
var db = event.target.result;
// Perform transaction operations
var transaction = db.transaction('storeName', 'readwrite');
var objectStore = transaction.objectStore('storeName');
// Insert data
objectStore.add({ id: 1, name: 'John Doe', age: 30 });
// Query data
var query = objectStore.get(1);
query.onsuccess = function(event) {
console.log(event.target.result);
};
};
// Error handling
request.onerror = function(event) {
console.error('Database error:', event.target.error);
};
IndexedDB Methods
1、indexedDB.open():Used to open an existing database or create a new database.
var request = indexedDB.open('databaseName', version);
2、db.createObjectStore():Create an object store (similar to a table) in the onupgradeneeded event.
var objectStore = db.createObjectStore('storeName', { keyPath: 'id' });
3、objectStore.add():Add data to an object store within a transaction.
objectStore.add({ id: 1, name: 'John Doe' });3、objectStore.get():Get data from an object store based on a key value.
var request = objectStore.get(1);
4、objectStore.put():Update an existing record, or insert if the record does not exist.
objectStore.put({ id: 1, name: 'John Updated' });5、objectStore.delete():Delete a record based on a key value.
objectStore.delete(1);
6、db.transaction():Create a transaction, specifying the object store name and transaction mode (readonly or readwrite).
var transaction = db.transaction(['storeName'], 'readwrite');
7、objectStore.createIndex():Create an index for fields in an object store for faster queries.
objectStore.createIndex('nameIndex', 'name', { unique: false });
IndexedDB Application Examples
The following is a complete IndexedDB example for creating a database, inserting data, querying data, and updating data.
Example
var request = indexedDB.open('myDatabase', 1);
// Triggered when the database version changes or on first creation
request.onupgradeneeded = function(event) {
var db = event.target.result;
// Create an object store (table) and set the primary key to 'id'
var objectStore = db.createObjectStore('customers', { keyPath: 'id' });
// Create an index for the 'name' field
objectStore.createIndex('name', 'name', { unique: false });
};
// Database opened successfully
request.onsuccess = function(event) {
var db = event.target.result;
// Insert data
var transaction = db.transaction(['customers'], 'readwrite');
var objectStore = transaction.objectStore('customers');
objectStore.add({ id: 1, name: 'John Doe', email: 'john@example.com' });
objectStore.add({ id: 2, name: 'Jane Doe', email: 'jane@example.com' });
transaction.oncomplete = function() {
console.log('Transaction completed: data added.');
};
transaction.onerror = function(event) {
console.error('Transaction failed:', event);
};
// Query data
var queryTransaction = db.transaction(['customers']);
var queryObjectStore = queryTransaction.objectStore('customers');
var query = queryObjectStore.get(1);
query.onsuccess = function(event) {
console.log('Customer:', event.target.result);
};
// Update data
var updateTransaction = db.transaction(['customers'], 'readwrite');
var updateObjectStore = updateTransaction.objectStore('customers');
var updatedCustomer = { id: 1, name: 'John Smith', email: 'johnsmith@example.com' };
updateObjectStore.put(updatedCustomer);
updateTransaction.oncomplete = function() {
console.log('Transaction completed: data updated.');
};
};
// Error handling
request.onerror = function(event) {
console.error('Database error:', event.target.error);
};
IndexedDB Use Cases
Offline storage: IndexedDB allows you to store data for access when there is no network connection, which is crucial for offline Web applications.
Caching: It can be used to store large amounts of cached data (such as files, images, videos) to improve application loading speed.
Complex data processing: Suitable for scenarios requiring storage and processing of large amounts of structured data, especially those needing indexing and query functionality.
Local database: IndexedDB can serve as a local database for front-end applications, storing user data, configuration information, application state, etc.
IndexedDB Advantages
Large storage capacity: Supports larger data storage (often hundreds of MB or more), much larger than localStorage's 5MB limit.
Rich data operations: Supports complex operations such as transactions, indexes, queries, and batch processing.
Offline support: Data is stored on the user's device, accessible offline and can be synced to the server.
IndexedDB Disadvantages
Complex API: Compared to simpler client-side storage like localStorage, the IndexedDB API is relatively complex and requires more code.
Asynchronous processing: Operations execute asynchronously; beginners may not be used to handling callbacks or Promises.
IndexedDB is very suitable for applications that need to store large amounts of structured data, especially Web applications that wish to support offline mode or handle complex queries.