Html5 Web Api Indexeddb
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.) through 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 those that want to support offline mode or handle complex queries in web applications.
### IndexedDB Features
* **Key-Value Storage**: Data is stored in object stores in the form of key-value pairs.
* **Transaction Support**: All data operations must be completed within transactions 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.
* **Version Control**: The database uses version numbers to manage the database schema (such as creating or modifying object stores).
* **Indexes**: Support creating indexes on data fields to speed up queries.
* **Offline Support**: Data can be persistently stored and accessed when the network is disconnected, making it very suitable for building offline web applications.
### IndexedDB Syntax
IndexedDB syntax is explained as follows:
// Open or create a database
var request = indexedDB.open('databaseName', version);
// Handle database upgrade
request.onupgradeneeded=function(event){
var db = event.target.result;
// Create object store (table) and set primary key
var objectStore = db.createObjectStore('storeName',{ keyPath:'id'});
// Create 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()οΌ**Creates an object store (similar to a table) in the onupgrad
YouTip