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 complex data objects (such as objects, arrays, files, etc.) to be stored as 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 ideal for applications that need to store large amounts of structured data, especially web apps that want to support offline mode or handle complex queries.
IndexedDB Features
- Key-Value Pair Storage: Data is stored in the form of key-value pairs in an object store.
- 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; event callbacks or Promises are used to handle results.
- Versioning: The database uses version numbers to manage its schema (such as creating or modifying object stores).
- Index: Supports creating indexes on data fields to speed up queries.
- Offline Support: Data can be stored persistently and accessed when offline, making it ideal for building offline web apps.
IndexedDB Syntax
The IndexedDB syntax is described below:
// Open or create a database
var
request
=
indexedDB.
open
(
'databaseName'
,
version
)
;
// Handle database upgrades
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 the database is opened 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 one.
var request = indexedDB.open('databaseName', version);
**2. db.createObjectStore():** Creates an object store (similar to a table) in the onupgradeneeded event.
var objectStore = db.createObjectStore('storeName', { keyPath: 'id' });
**3. objectStore.add():** Adds data to an object store within a transaction.
objectStore.add({ id: 1, name: 'John Doe' });
**3. objectStore.get():** Gets data from an object store by key.
var request = objectStore.get(1);
**4. objectStore.put():** Updates an existing record, or inserts one if the record does not exist.
objectStore.put({ id: 1, name: 'John Updated' });
**5. objectStore.delete():** Deletes a record by key.
objectStore.delete(1);
**6. db.transaction():** Creates a transaction, specifying the object store name and transaction mode (readonly or readwrite).
var transaction = db.transaction(['storeName'], 'readwrite');
**7. objectStore.createIndex():** Creates an index on a field in the object store for faster queries.
objectStore.createIndex('nameIndex', 'name', { unique: false });
IndexedDB Application Example
The following is a complete IndexedDB example that creates a database, inserts data, queries data, and updates data.
Example
// Open or create a database
var
request
=
indexedDB.
open
(
'myDatabase'
,
1
)
;
// Triggered when the database version changes or the database is created for the first time
request.
onupgradeneeded
=
function
(
event
)
{
var
db
=
event.
target
.
result
;
// Create an object store (table) with 'id' as the primary key
var
objectStore
=
db.
createObjectStore
(
'customers'
,
{
keyPath
:
'id'
}
)
;
// Create an index on 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'
,
:
'john@example.com'
}
)
;
objectStore.
add
(
{
id
:
2
,
name
:
'Jane Doe'
,
:
'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'
,
:
'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 essential for offline web apps.
-
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 that need to store and process large amounts of structured data, especially where indexing and query capabilities are required.
-
Local database: IndexedDB can serve as a local database for front-end applications, storing user data, configuration information, application state, and so on.
Advantages of IndexedDB
-
Large-capacity storage: Supports larger data storage (often hundreds of MB or more), much greater than the 5MB limit of localStorage.
-
Rich data operations: Supports complex operations such as transactions, indexing, queries, and batch processing.
-
Offline support: Data is stored on the user's device, can be accessed offline, and can be synchronized to the server.
Disadvantages of IndexedDB
-
Complex API: Compared with simple client-side storage such as localStorage, the IndexedDB API is relatively complex and requires more code.
-
Asynchronous processing: Operations are executed asynchronously, so beginners may not be accustomed to handling callbacks or Promises.
-
IndexedDB is ideal for applications that need to store large amounts of structured data, especially web apps that want to support offline mode or handle complex queries.