IndexedDB 是一種基於瀏覽器的 NoSQL 數據庫,用於在客户端持久化存儲大量結構化數據。
IndexedDB 允許通過鍵值對存儲複雜的數據對象(如對象、數組、文件等),並支持事務、索引、版本控制和複雜查詢操作。
IndexedDB 是異步的,不會阻塞主線程,適合離線應用程序、緩存等場景。
IndexedDB 非常適合需要存儲大量結構化數據的應用程序,尤其是那些希望支持離線模式或處理複雜查詢的 Web 應用。
IndexedDB 特性
- 鍵值對存儲:數據以鍵值對的形式存儲在對象存儲(object store)中。
- 事務支持:所有數據操作必須在事務內完成,以確保數據一致性和完整性。
- 異步 API:所有操作都是異步的,不會阻塞 UI 線程,使用事件回調或 Promises 來處理結果。
- 版本控制:數據庫使用版本號來管理數據庫的架構(如創建或修改對象存儲)。
- 索引:支持對數據的字段建立索引,以加快查詢速度。
- 離線支持:數據可以持久化存儲並在斷網情況下繼續訪問,非常適合構建離線 Web 應用。
IndexedDB 語法
IndexedDB 語法説明如下:
// 打開或創建一個數據庫
var request = indexedDB.open('databaseName',version);
// 處理數據庫升級
request.onupgradeneeded = function(event) {
var db = event.target.result;
// 創建對象存儲(表)並設置主鍵
var objectStore = db.createObjectStore('storeName', { keyPath: 'id' });
// 創建索引
objectStore.createIndex('fieldName', 'fieldName', { unique: false });
};
// 數據庫打開成功時的回調
request.onsuccess = function(event) {
var db = event.target.result;
// 進行事務操作
var transaction = db.transaction('storeName', 'readwrite');
var objectStore = transaction.objectStore('storeName');
// 插入數據
objectStore.add({ id: 1, name: 'John Doe',age: 30 });
// 查詢數據
var query = objectStore.get(1);
query.onsuccess = function(event) {
console.log(event.target.result);
};
};
// 錯誤處理
request.onerror = function(event) {
console.error('Database error:', event.target.error);
};
IndexedDB 方法
1、indexedDB.open():用於打開現有數據庫或創建新數據庫。
var request = indexedDB.open('databaseName', version);
2、db.createObjectStore():在 onupgradeneeded 事件中創建對象存儲(類似表)。
var objectStore = db.createObjectStore('storeName', { keyPath: 'id' });
3、objectStore.add():在事務中向對象存儲中添加數據。
objectStore.add({ id: 1, name: 'John Doe' });
3、objectStore.get():根據鍵值從對象存儲中獲取數據。
var request = objectStore.get(1);
4、objectStore.put():更新現有記錄,若記錄不存在則插入。
objectStore.put({ id: 1, name: 'John Updated' });
5、objectStore.delete():根據鍵值刪除記錄。
objectStore.delete(1);
6、db.transaction():創建事務,指定對象存儲名稱和事務模式(readonly 或 readwrite)。
var transaction = db.transaction(['storeName'], 'readwrite');
7、objectStore.createIndex():為對象存儲中的字段創建索引,以便更快的查詢。
objectStore.createIndex('nameIndex', 'name', { unique: false });
IndexedDB 應用實例
以下是一個完整的 IndexedDB 實例,用於創建數據庫、插入數據、查詢數據並更新數據。
實例
// 打開或創建數據庫
var request = indexedDB.open('myDatabase',1);
// 如果數據庫版本變化或首次創建時觸發
request.onupgradeneeded = function(event) {
var db = event.target.result;
// 創建對象存儲(表),設置主鍵為 'id'
var objectStore = db.createObjectStore('customers', { keyPath: 'id' });
// 為 'name' 字段創建索引
objectStore.createIndex('name', 'name', { unique: false });
};
// 打開數據庫成功
request.onsuccess = function(event) {
var db = event.target.result;
// 插入數據
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);
};
// 查詢數據
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);
};
// 更新數據
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.');
};
};
// 錯誤處理
request.onerror = function(event) {
console.error('Database error:', event.target.error);
};
IndexedDB 使用場景
- 離線存儲:IndexedDB 允許你存儲數據以便在沒有網絡連接時訪問,這對於離線 Web 應用至關重要。
- 緩存:可以用於存儲大量緩存數據(如文件、圖片、視頻),提升應用的加載速度。
- 複雜數據處理:適用於需要存儲和處理大量結構化數據的場景,尤其是需要索引和查詢功能。
- 本地數據庫:IndexedDB 可以作為前端應用的本地數據庫,存儲用户數據、配置信息、應用狀態等。
IndexedDB 的優勢
- 大容量存儲:支持更大數據存儲(常常可以達到幾百 MB 或更多),比 localStorage 的 5MB 限制大得多。
- 豐富的數據操作:支持事務、索引、查詢、批量處理等複雜操作。
- 離線支持:數據保存在用户設備上,可以離線訪問並同步到服務器。
IndexedDB 的劣勢
- API 複雜:相比 localStorage 等簡單的客户端存儲,IndexedDB API 相對複雜,需要更多的代碼。
- 異步處理:操作異步執行,初學者可能會不習慣處理回調或 Promise。
- IndexedDB 非常適合需要存儲大量結構化數據的應用程序,尤其是那些希望支持離線模式或處理複雜查詢的 Web 應用。