溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

HTML5的IndexedDB索引數(shù)據(jù)庫實例分析

發(fā)布時間:2022-03-08 10:14:43 來源:億速云 閱讀:275 作者:iii 欄目:web開發(fā)

本篇內(nèi)容主要講解“HTML5的IndexedDB索引數(shù)據(jù)庫實例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“HTML5的IndexedDB索引數(shù)據(jù)庫實例分析”吧!

介紹

IndexedDB是HTML5 WEB數(shù)據(jù)庫,允許HTML5 WEB應(yīng)用在用戶瀏覽器端存儲數(shù)據(jù)。對于應(yīng)用來說IndexedDB非常強大,有用,可以在客戶端的chrome,IE,F(xiàn)irefox等WEB瀏覽器中存儲大量數(shù)據(jù),下面簡單介紹一下IndexedDB的基本概念。什么是IndexedDB IndexedDB,HTML5新的數(shù)據(jù)存儲,可以在客戶端存儲,操作數(shù)據(jù),可以使應(yīng)用加載地交換,更好地響應(yīng)。它具有關(guān)系型數(shù)據(jù)庫,擁有數(shù)據(jù)表,索引。它創(chuàng)建了數(shù)據(jù)類型和簡單的JavaScript持久對象的對象,每個對象可以有索引,可以有效地查詢和遍歷整個集合。此處為您提供了如何在Web應(yīng)用程序中使用IndexedDB的真實示例。開始我們需要在執(zhí)行前包含下面的代碼

JavaScript代碼將內(nèi)容復(fù)制到

var  indexedDB  =  window .indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   

// window.IDB對象的前綴   

var  IDBTransaction  =  window .IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;   

var  IDBKeyRange  =  window .IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   

如果(!indexedDB){   

alert(“您的瀏覽器不支持穩(wěn)定版本的IndexedDB?!保?nbsp;  

}  

:IndexedDB

在創(chuàng)建數(shù)據(jù)庫之前,我們首先需要為數(shù)據(jù)庫創(chuàng)建數(shù)據(jù),假設(shè)我們有如下的用戶信息:

JavaScript代碼將內(nèi)容復(fù)制到

var  userData  = [   

{id:“ 1”,名稱:“ Tapas”,年齡:33,電子郵件:“ tapas@example.com”},   

{id:“ 2”,名稱:“ Bidulata”,年齡:55,電子郵件:“ bidu@home.com”}   

];  

現(xiàn)在我們需要用open()方法打開我們的數(shù)據(jù)庫:

JavaScript代碼將內(nèi)容復(fù)制到

var db;   

var  request  =  indexedDB .open(“ databaseName”,1);   

request.onerror  = 函數(shù)(e){   

console.log(“ error:”,e);   

};   

request.onsuccess  = 函數(shù)(e){   

db  =  request .result;   

console.log(“ success:” + db);   

};   

request.onupgradeneeded  = 函數(shù)(e){   

}  

如上所示,我們已經(jīng)打開了稱為“數(shù)據(jù)庫名稱”,指定版本號的數(shù)據(jù)庫,open()方法有兩個參數(shù):1.第一個參數(shù)是數(shù)據(jù)庫名稱,它會檢測名稱為“數(shù)據(jù)庫名稱”的數(shù)據(jù)庫是否已經(jīng)存在,如果存在則打開它,否則創(chuàng)建新的數(shù)據(jù)庫。2.第二個參數(shù)是數(shù)據(jù)庫的版本,用于用戶更新數(shù)據(jù)庫結(jié)構(gòu)。的onSuccess處理發(fā)生成功事件時“的onSuccess”被觸發(fā),如果所有成功的請求都在此處理,我們可以通過賦值給DB變量保存請求的結(jié)果供以后使用。的onerror的處理程序發(fā)生錯誤事件時“的onerror”被觸發(fā),如果打開數(shù)據(jù)庫的過程中失敗。Onupgradeneeded處理程序如果你想更新數(shù)據(jù)庫(創(chuàng)建,刪除或修改數(shù)據(jù)庫),那么您必須實現(xiàn)onupgradeneeded處理程序,使您可以在數(shù)據(jù)庫中做任何更改。在“ onupgradeneeded”處理程序中是可以更改數(shù)據(jù)庫的結(jié)構(gòu)的唯一地方。創(chuàng)建和添加數(shù)據(jù)到表:IndexedDB使用對象存儲來存儲數(shù)據(jù),而不是通過表。索引一個值存儲在對象存儲中,它與一個鍵相關(guān)聯(lián)。它允許我們創(chuàng)建任何對象存儲索引。索引允許我們訪問存儲在對象存儲中的值。下面的代碼顯示了如何創(chuàng)建對象存儲并插入預(yù)先準(zhǔn)備好的數(shù)據(jù):

JavaScript代碼將內(nèi)容復(fù)制到

request.onupgradeneeded  = 函數(shù)(事件){   

var  objectStore  =  event .target.result.createObjectStore(“ users”,{keyPath:“ id”});   

對于(var i in userData){   

objectStore.add(userData [i]);    

}   

}  

我們使用createObjectStore()方法創(chuàng)建一個對象存儲。此方法接受兩個參數(shù):-存儲的名稱和參數(shù)對象。在這里,我們有一個稱為“ users”的對象存儲,并定義了keyPath,這是對象唯一在這里,我們使用“ id”作為keyPath,這個值在對象存儲中是唯一的,我們必須確保該“ ID”的屬性在對象存儲中的每個對象中存在。一旦創(chuàng)建了對象存儲,我們可以開始使用循環(huán)添加數(shù)據(jù)進(jìn)去。手動將數(shù)據(jù)添加到表:我們可以手動添加額外的數(shù)據(jù)到數(shù)據(jù)庫中。

JavaScript代碼將內(nèi)容復(fù)制到

函數(shù)Add(){   

var  request  =  db .transaction([“ users”],“ readwrite”)。objectStore(“ users”)   

.add({id:“ 3”,名稱:“ Gautam”,年齡:30,電子郵件:“ gautam@store.org”});   

request.onsuccess  = 函數(shù)(e){   

alert(“ Gautam已添加到數(shù)據(jù)庫?!保?   

};   

request.onerror  = 函數(shù)(e){   

alert(“無法添加信息。”);    

}   

}  

該transaction()方法是指定我們想要進(jìn)行事務(wù)處理的對象存儲。transaction()方法接受3個參數(shù)(之前,在我們在數(shù)據(jù)庫中做任何的CRUD操作(讀,寫,修改),必須使用事務(wù)。第二個和第三個是可選的)。第一個是我們要處理的對象存儲的列表,第二個指定我們是否要替換/讀取,第三個是版本變化。從表中讀取數(shù)據(jù)的get()方法用于從對象存儲中檢索數(shù)據(jù)。我們之前已經(jīng)設(shè)置對象的ID作為的的keyPath,所以GET()方法將查找具有相同的ID值的對象。下面的代碼將返回我們命名為“Bidulata ”的對象:

JavaScript代碼將內(nèi)容復(fù)制到

函數(shù)Read(){   

var  objectStore  =  db .transaction([“ users”])。objectStore(“ users”);   

var  request  =  objectStore .get(“ 2”);   

request.onerror  = 函數(shù)(事件){   

alert(“無法從數(shù)據(jù)庫中檢索數(shù)據(jù)!”);   

};   

request.onsuccess  = 函數(shù)(事件){    

if(request.result){   

alert(“名稱:” + request.result.name +“,年齡:” + request.result.age +“,電子郵件:” + request.result.email);   

}其他{   

alert(“在您的數(shù)據(jù)庫中找不到Bidulata!”);    

}   

};   

}  

從表中讀取所有數(shù)據(jù)

下面的方法檢索表中的所有數(shù)據(jù)。此處我們使用游標(biāo)來檢索對象存儲中的所有數(shù)據(jù):

JavaScript代碼將內(nèi)容復(fù)制到

函數(shù)ReadAll(){   

var  objectStore  =  db .transaction(“ users”)。objectStore(“ users”);    

var  req  =  objectStore .openCursor();   

req.onsuccess  = 函數(shù)(事件){   

db.close();   

var  res  =  event .target.result;   

如果(res){   

alert(“ Key” + res.key +“是” + res.value.name +“,年齡:” + res.value.age +“,電子郵件:” + res.value.email);   

res.continue();   

}   

};   

req.onerror  = 函數(shù) (e){   

console.log(“錯誤獲?。骸?,e);   

};    

}  

該openCursor()用于遍歷數(shù)據(jù)庫中的多個記錄。在continue()函數(shù)中繼續(xù)讀取下一條記錄。刪除表中的記錄下面的方法從對象中刪除記錄。

JavaScript代碼將內(nèi)容復(fù)制到

函數(shù)Remove(){    

var  request  =  db .transaction([“ users”],“ readwrite”)。objectStore(“ users”)。delete(“ 1”);   

request.onsuccess  = 函數(shù)(事件){   

alert(“ Tapas的條目已從您的數(shù)據(jù)庫中刪除。”);   

};   

}  

我們將對象的keyPath作為參數(shù)傳遞給delete()方法。最終代碼下面的方法從對象源中刪除一條記錄:

JavaScript代碼將內(nèi)容復(fù)制到

<!DOCTYPE html >  

<頭>  

< meta http-equiv = “ Content-Type” content = “ text / html; charset = utf-8” />     

< title > IndexedDB </ title >  

<腳本類型= “ text / javascript” >   

var  indexedDB  =  window .indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;   

// window.IDB對象的前綴   

var  IDBTransaction  =  window .IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;   

var  IDBKeyRange  =  window .IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange   

如果(!indexedDB){   

alert(“您的瀏覽器不支持穩(wěn)定版本的IndexedDB?!保?nbsp;  

}   

var  customerData  = [   

{id:“ 1”,名稱:“ Tapas”,年齡:33,電子郵件:“ tapas@example.com”},   

{id:“ 2”,名稱:“ Bidulata”,年齡:55,電子郵件:“ bidu@home.com”}   

];   

var db;   

var  request  =  indexedDB .open(“ newDatabase”,1);   

request.onerror  = 函數(shù)(e){   

console.log(“ error:”,e);   

};   

request.onsuccess  = 函數(shù)(e){   

db  =  request .result;   

console.log(“ success:” + db);   

};   

request.onupgradeneeded  = 函數(shù)(事件){   

}   

request.onupgradeneeded  = 函數(shù)(事件){   

var  objectStore  =  event .target.result.createObjectStore(“ users”,{keyPath:“ id”});   

對于(var i in userData){   

objectStore.add(userData [i]);    

}   

}   

函數(shù)Add(){   

var  request  =  db .transaction([“ users”],“ readwrite”)   

.objectStore(“用戶”)   

.add({id:“ 3”,名稱:“ Gautam”,年齡:30,電子郵件:“ gautam@store.org”});   

request.onsuccess  = 函數(shù)(e){   

alert(“ Gautam已添加到數(shù)據(jù)庫。”);   

};   

request.onerror  = 函數(shù)(e){   

alert(“無法添加信息。”);    

}   

}   

函數(shù)Read(){   

var  objectStore  =  db .transaction(“ users”)。objectStore(“ users”);   

var  request  =  objectStore .get(“ 2”);   

request.onerror  = 函數(shù)(事件){   

alert(“無法從數(shù)據(jù)庫中檢索數(shù)據(jù)!”);   

};   

request.onsuccess  = 函數(shù)(事件){    

if(request.result){   

alert(“名稱:” + request.result.name +“,年齡:” + request.result.age +“,電子郵件:” + request.result.email);   

}其他{   

alert(“在您的數(shù)據(jù)庫中找不到Bidulata!”);    

}   

};   

}   

函數(shù)ReadAll(){   

var  objectStore  =  db .transaction(“ users”)。objectStore(“ users”);    

var  req  =  objectStore .openCursor();   

req.onsuccess  = 函數(shù)(事件){   

db.close();   

var  res  =  event .target.result;   

如果(res){   

alert(“ Key” + res.key +“是” + res.value.name +“,年齡:” + res.value.age +“,電子郵件:” + res.value.email);   

res.continue();   

}   

};   

req.onerror  = 函數(shù) (e){   

console.log(“錯誤獲?。骸?,e);   

};    

}   

函數(shù)Remove(){    

var  request  =  db .transaction([“ users”],“ readwrite”)。objectStore(“ users”)。delete(“ 1”);   

request.onsuccess  = 函數(shù)(事件){   

alert(“ Tapas的條目已從您的數(shù)據(jù)庫中刪除?!保?   

};   

}   

</腳本>  

</頭>  

<身體>  

< button onclick = “ Add()” >添加記錄</ button >   

< button onclick = “ Remove()” >刪除記錄</ button >   

< button onclick = “ Read()” >檢索單個記錄</ button >   

< button onclick = “ ReadAll()” >檢索所有記錄</ button >   

</ body >  

</ html >  

localStorage是不帶鎖功能的。那么要實現(xiàn)前端的數(shù)據(jù)共享并且需要鎖功能那就需要使用其他本存儲方式,索引indexDB。indededDB使用的是事務(wù)處理的機制,那實際上就是鎖功能?! ∽鲞@個測試需要先簡單的封裝下indexedDB的操作,因為indexedDB的連接比較麻煩,而且兩個測試頁面都需要用到

JavaScript代碼將內(nèi)容復(fù)制到

//db.js   

//封裝事務(wù)操作   

IDBDatabase.prototype.doTransaction =函數(shù)(f){   

  f(this.transaction([“ Obj”],“ readwrite”)。objectStore(“ Obj”));;   

};   

//連接數(shù)據(jù)庫,成功后調(diào)用main函數(shù)   

(功能(){   

  //打開數(shù)據(jù)庫   

  var  cn = indexedDB .open(“ TestDB”,1);   

  //創(chuàng)建數(shù)據(jù)對象   

  cn.onupgradeneeded =函數(shù)(e){   

    e.target.result.createObjectStore(“ Obj”);   

  };   

  //數(shù)據(jù)庫連接成功   

  cn.onsuccess =函數(shù)(e){   

    main(e.target.result);   

  };   

})();   

  接下來是兩個測試頁面   

<腳本src = “ db.js” > </腳本>   

<腳本>  

//a.html   

函數(shù)main(e){   

  (函數(shù)callee(){   

    //開始一個事務(wù)   

    e.doTransaction(function(e){   

      e.put(1,“ test”); //設(shè)置test的數(shù)值1   

      e.put(2,“ test”); //設(shè)置test的數(shù)值2   

    });   

    setTimeout(callee);   

  })();   

};   

</腳本>  

<腳本src = “ db.js” > </腳本>   

<腳本>  

//b.html   

函數(shù)main(e){   

  (函數(shù)callee(){   

    //開始一個事務(wù)   

    e.doTransaction(function(e){   

      //獲取測試的值   

      e.get(“ test”). onsuccess =函數(shù)(e){   

        console.log(e.target.result);   

      };   

    });   

    setTimeout(callee);   

  })();   

};   

</腳本>  

把本地存儲換成indexedDB事務(wù)處理。但是結(jié)果就不同

測試的時候b.html中可能不會立即有輸出,因為indexedDB正忙著處理a.html東西,b.html事務(wù)丟了了事務(wù)丟了中等待。但是無論如何,輸出結(jié)果也不會是1這個值。因為indexedDB的最小處理單位是事務(wù),而不是localStorage那以表達(dá)式為單位。這樣只要把鎖和解鎖之間需要處理的東西放入一個事務(wù)中即可實現(xiàn)。另外,瀏覽器對indexedDB的支持不如localStorage,所以使用時還得考慮瀏覽器兼容。

到此,相信大家對“HTML5的IndexedDB索引數(shù)據(jù)庫實例分析”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI