瀏覽器數(shù)據(jù)庫IndexedDB入門教程
一、概述
隨著瀏覽器的功能不斷增強(qiáng),越來越多的網(wǎng)站開始考慮,將大量數(shù)據(jù)儲(chǔ)存在客戶端,這樣可以減少從服務(wù)器獲取數(shù)據(jù),直接從本地獲取數(shù)據(jù)。
現(xiàn)有的瀏覽器數(shù)據(jù)儲(chǔ)存方案,都不適合儲(chǔ)存大量數(shù)據(jù):Cookie 的大小不超過4KB,且每次請(qǐng)求都會(huì)發(fā)送回服務(wù)器;LocalStorage 在 2.5MB 到 10MB 之間(各家瀏覽器不同),而且不提供搜索功能,不能建立自定義的索引。所以,需要一種新的解決方案,這就是 IndexedDB 誕生的背景。
通俗地說,IndexedDB 就是瀏覽器提供的本地?cái)?shù)據(jù)庫,它可以被網(wǎng)頁腳本創(chuàng)建和操作。IndexedDB 允許儲(chǔ)存大量數(shù)據(jù),提供查找接口,還能建立索引。這些都是 LocalStorage 所不具備的。就數(shù)據(jù)庫類型而言,IndexedDB 不屬于關(guān)系型數(shù)據(jù)庫(不支持 SQL 查詢語句),更接近 NoSQL 數(shù)據(jù)庫。
IndexedDB 具有以下特點(diǎn)。
- 鍵值對(duì)儲(chǔ)存。 IndexedDB 內(nèi)部采用對(duì)象倉庫(object store)存放數(shù)據(jù)。所有類型的數(shù)據(jù)都可以直接存入,包括 JavaScript 對(duì)象。對(duì)象倉庫中,數(shù)據(jù)以"鍵值對(duì)"的形式保存,每一個(gè)數(shù)據(jù)記錄都有對(duì)應(yīng)的主鍵,主鍵是***的,不能有重復(fù),否則會(huì)拋出一個(gè)錯(cuò)誤。
- 異步。 IndexedDB 操作時(shí)不會(huì)鎖死瀏覽器,用戶依然可以進(jìn)行其他操作,這與 LocalStorage 形成對(duì)比,后者的操作是同步的。異步設(shè)計(jì)是為了防止大量數(shù)據(jù)的讀寫,拖慢網(wǎng)頁的表現(xiàn)。
- 支持事務(wù)。 IndexedDB 支持事務(wù)(transaction),這意味著一系列操作步驟之中,只要有一步失敗,整個(gè)事務(wù)就都取消,數(shù)據(jù)庫回滾到事務(wù)發(fā)生之前的狀態(tài),不存在只改寫一部分?jǐn)?shù)據(jù)的情況。
- 同源限制 IndexedDB 受到同源限制,每一個(gè)數(shù)據(jù)庫對(duì)應(yīng)創(chuàng)建它的域名。網(wǎng)頁只能訪問自身域名下的數(shù)據(jù)庫,而不能訪問跨域的數(shù)據(jù)庫。
- 儲(chǔ)存空間大 IndexedDB 的儲(chǔ)存空間比 LocalStorage 大得多,一般來說不少于 250MB,甚至沒有上限。
- 支持二進(jìn)制儲(chǔ)存。 IndexedDB 不僅可以儲(chǔ)存字符串,還可以儲(chǔ)存二進(jìn)制數(shù)據(jù)(ArrayBuffer 對(duì)象和 Blob 對(duì)象)。
二、基本概念
IndexedDB 是一個(gè)比較復(fù)雜的 API,涉及不少概念。它把不同的實(shí)體,抽象成一個(gè)個(gè)對(duì)象接口。學(xué)習(xí)這個(gè) API,就是學(xué)習(xí)它的各種對(duì)象接口。
- 數(shù)據(jù)庫:IDBDatabase 對(duì)象
- 對(duì)象倉庫:IDBObjectStore 對(duì)象
- 索引: IDBIndex 對(duì)象
- 事務(wù): IDBTransaction 對(duì)象
- 操作請(qǐng)求:IDBRequest 對(duì)象
- 指針: IDBCursor 對(duì)象
- 主鍵集合:IDBKeyRange 對(duì)象
下面是一些主要的概念。
數(shù)據(jù)庫
數(shù)據(jù)庫是一系列相關(guān)數(shù)據(jù)的容器。每個(gè)域名(嚴(yán)格的說,是協(xié)議 + 域名 + 端口)都可以新建任意多個(gè)數(shù)據(jù)庫。
IndexedDB 數(shù)據(jù)庫有版本的概念。同一個(gè)時(shí)刻,只能有一個(gè)版本的數(shù)據(jù)庫存在。如果要修改數(shù)據(jù)庫結(jié)構(gòu)(新增或刪除表、索引或者主鍵),只能通過升級(jí)數(shù)據(jù)庫版本完成。
對(duì)象倉庫
每個(gè)數(shù)據(jù)庫包含若干個(gè)對(duì)象倉庫(object store)。它類似于關(guān)系型數(shù)據(jù)庫的表格。
數(shù)據(jù)記錄
對(duì)象倉庫保存的是數(shù)據(jù)記錄。每條記錄類似于關(guān)系型數(shù)據(jù)庫的行,但是只有主鍵和數(shù)據(jù)體兩部分。主鍵用來建立默認(rèn)的索引,必須是不同的,否則會(huì)報(bào)錯(cuò)。主鍵可以是數(shù)據(jù)記錄里面的一個(gè)屬性,也可以指定為一個(gè)遞增的整數(shù)編號(hào)。
{ id: 1, text: 'foo' }
上面的對(duì)象中,id屬性可以當(dāng)作主鍵。
數(shù)據(jù)體可以是任意數(shù)據(jù)類型,不限于對(duì)象。
索引
為了加速數(shù)據(jù)的檢索,可以在對(duì)象倉庫里面,為不同的屬性建立索引。
事務(wù)
數(shù)據(jù)記錄的讀寫和刪改,都要通過事務(wù)完成。事務(wù)對(duì)象提供error、abort和complete三個(gè)事件,用來監(jiān)聽操作結(jié)果。
三、操作流程
IndexedDB 數(shù)據(jù)庫的各種操作,一般是按照下面的流程進(jìn)行的。這個(gè)部分只給出簡(jiǎn)單的代碼示例,用于快速上手,詳細(xì)的各個(gè)對(duì)象的 API 請(qǐng)看這里。
打開數(shù)據(jù)庫
使用 IndexedDB 的***步是打開數(shù)據(jù)庫,使用indexedDB.open()方法。
- var request = window.indexedDB.open(databaseName, version);
這個(gè)方法接受兩個(gè)參數(shù),***個(gè)參數(shù)是字符串,表示數(shù)據(jù)庫的名字。如果指定的數(shù)據(jù)庫不存在,就會(huì)新建數(shù)據(jù)庫。第二個(gè)參數(shù)是整數(shù),表示數(shù)據(jù)庫的版本。如果省略,打開已有數(shù)據(jù)庫時(shí),默認(rèn)為當(dāng)前版本;新建數(shù)據(jù)庫時(shí),默認(rèn)為1。
indexedDB.open()方法返回一個(gè) IDBRequest 對(duì)象。這個(gè)對(duì)象通過三種事件error、success、upgradeneeded,處理打開數(shù)據(jù)庫的操作結(jié)果。
error 事件
error事件表示打開數(shù)據(jù)庫失敗。
- request.onerror = function (event) {
- console.log('數(shù)據(jù)庫打開報(bào)錯(cuò)');
- };
success 事件
success事件表示成功打開數(shù)據(jù)庫。
- var db;
- request.onsuccess = function (event) {
- db = request.result;
- console.log('數(shù)據(jù)庫打開成功');
- };
這時(shí),通過request對(duì)象的result屬性拿到數(shù)據(jù)庫對(duì)象。
upgradeneeded 事件
如果指定的版本號(hào),大于數(shù)據(jù)庫的實(shí)際版本號(hào),就會(huì)發(fā)生數(shù)據(jù)庫升級(jí)事件upgradeneeded。
- var db;
- request.onupgradeneeded = function (event) {
- db = event.target.result;
- }
這時(shí)通過事件對(duì)象的target.result屬性,拿到數(shù)據(jù)庫實(shí)例。
新建數(shù)據(jù)庫
新建數(shù)據(jù)庫與打開數(shù)據(jù)庫是同一個(gè)操作。如果指定的數(shù)據(jù)庫不存在,就會(huì)新建。不同之處在于,后續(xù)的操作主要在upgradeneeded事件的監(jiān)聽函數(shù)里面完成,因?yàn)檫@時(shí)版本從無到有,所以會(huì)觸發(fā)這個(gè)事件。
通常,新建數(shù)據(jù)庫以后,***件事是新建對(duì)象倉庫(即新建表)。
- request.onupgradeneeded = function(event) {
- db = event.target.result;
- var objectStore = db.createObjectStore('person', { keyPath: 'id' });
- }
上面代碼中,數(shù)據(jù)庫新建成功以后,新增一張叫做person的表格,主鍵是id。
更好的寫法是先判斷一下,這張表格是否存在,如果不存在再新建。
- request.onupgradeneeded = function (event) {
- db = event.target.result;
- var objectStore;
- if (!db.objectStoreNames.contains('person')) {
- objectStore = db.createObjectStore('person', { keyPath: 'id' });
- }
- }
主鍵(key)是默認(rèn)建立索引的屬性。比如,數(shù)據(jù)記錄是{ id: 1, name: '張三' },那么id屬性可以作為主鍵。主鍵也可以指定為下一層對(duì)象的屬性,比如{ foo: { bar: 'baz' } }的foo.bar也可以指定為主鍵。
如果數(shù)據(jù)記錄里面沒有合適作為主鍵的屬性,那么可以讓 IndexedDB 自動(dòng)生成主鍵。
- var objectStore = db.createObjectStore(
- 'person',
- { autoIncrement: true }
- );
上面代碼中,指定主鍵為一個(gè)遞增的整數(shù)。
新建對(duì)象倉庫以后,下一步可以新建索引。
- request.onupgradeneeded = function(event) {
- db = event.target.result;
- var objectStore = db.createObjectStore('person', { keyPath: 'id' });
- objectStore.createIndex('name', 'name', { unique: false });
- objectStore.createIndex('email', 'email', { unique: true });
- }
上面代碼中,IDBObject.createIndex()的三個(gè)參數(shù)分別為索引名稱、索引所在的屬性、配置對(duì)象(說明該屬性是否包含重復(fù)的值)。
新增數(shù)據(jù)
新增數(shù)據(jù)指的是向?qū)ο髠}庫寫入數(shù)據(jù)記錄。這需要通過事務(wù)完成。
- function add() {
- var request = db.transaction(['person'], 'readwrite')
- .objectStore('person')
- .add({ id: 1, name: '張三', age: 24, email: 'zhangsan@example.com' });
- request.onsuccess = function (event) {
- console.log('數(shù)據(jù)寫入成功');
- };
- request.onerror = function (event) {
- console.log('數(shù)據(jù)寫入失敗');
- }
- }
- add();
上面代碼中,寫入數(shù)據(jù)需要新建一個(gè)事務(wù)。新建時(shí)必須指定表格名稱和操作模式("只讀"或"讀寫")。新建事務(wù)以后,通過IDBTransaction.objectStore(name)方法,拿到 IDBObjectStore 對(duì)象,再通過表格對(duì)象的add()方法,向表格寫入一條記錄。
寫入操作是一個(gè)異步操作,通過監(jiān)聽連接對(duì)象的success事件和error事件,了解是否寫入成功。
讀取數(shù)據(jù)
讀取數(shù)據(jù)也是通過事務(wù)完成。
- function read() {
- var transaction = db.transaction(['person']);
- var objectStore = transaction.objectStore('person');
- var request = objectStore.get(1);
- request.onerror = function(event) {
- console.log('事務(wù)失敗');
- };
- request.onsuccess = function( event) {
- if (request.result) {
- console.log('Name: ' + request.result.name);
- console.log('Age: ' + request.result.age);
- console.log('Email: ' + request.result.email);
- } else {
- console.log('未獲得數(shù)據(jù)記錄');
- }
- };
- }
- read();
上面代碼中,objectStore.get()方法用于讀取數(shù)據(jù),參數(shù)是主鍵的值。
遍歷數(shù)據(jù)
遍歷數(shù)據(jù)表格的所有記錄,要使用指針對(duì)象 IDBCursor。
- function readAll() {
- var objectStore = db.transaction('person').objectStore('person');
- objectStore.openCursor().onsuccess = function (event) {
- var cursor = event.target.result;
- if (cursor) {
- console.log('Id: ' + cursor.key);
- console.log('Name: ' + cursor.value.name);
- console.log('Age: ' + cursor.value.age);
- console.log('Email: ' + cursor.value.email);
- cursor.continue();
- } else {
- console.log('沒有更多數(shù)據(jù)了!');
- }
- };
- }
- readAll();
上面代碼中,新建指針對(duì)象的openCursor()方法是一個(gè)異步操作,所以要監(jiān)聽success事件。
更新數(shù)據(jù)
更新數(shù)據(jù)要使用IDBObject.put()方法。
- function update() {
- var request = db.transaction(['person'], 'readwrite')
- .objectStore('person')
- .put({ id: 1, name: '李四', age: 35, email: 'lisi@example.com' });
- request.onsuccess = function (event) {
- console.log('數(shù)據(jù)更新成功');
- };
- request.onerror = function (event) {
- console.log('數(shù)據(jù)更新失敗');
- }
- }
- update();
上面代碼中,put()方法自動(dòng)更新了主鍵為1的記錄。
刪除數(shù)據(jù)
IDBObjectStore.delete()方法用于刪除記錄。
- function remove() {
- var request = db.transaction(['person'], 'readwrite')
- .objectStore('person')
- .delete(1);
- request.onsuccess = function (event) {
- console.log('數(shù)據(jù)刪除成功');
- };
- }
- remove();
使用索引
索引的意義在于,可以讓你搜索任意字段,也就是說從任意字段拿到數(shù)據(jù)記錄。如果不建立索引,默認(rèn)只能搜索主鍵(即從主鍵取值)。
假定新建表格的時(shí)候,對(duì)name字段建立了索引。
- objectStore.createIndex('name', 'name', { unique: false });
現(xiàn)在,就可以從name找到對(duì)應(yīng)的數(shù)據(jù)記錄了。
- var transaction = db.transaction(['person'], 'readonly');
- var store = transaction.objectStore('person');
- var index = store.index('name');
- var request = index.get('李四');
- request.onsuccess = function (e) {
- var result = e.target.result;
- if (result) {
- // ...
- } else {
- // ...
- }
- }





















