深入解析HTML5的IndexedDB索引數(shù)據(jù)庫
來源:易賢網(wǎng) 閱讀:1576 次 日期:2016-07-09 10:31:00
溫馨提示:易賢網(wǎng)小編為您整理了“深入解析HTML5的IndexedDB索引數(shù)據(jù)庫”,方便廣大網(wǎng)友查閱!

這篇文章主要介紹了深入解析HTML5中的IndexedDB索引數(shù)據(jù)庫,包括事務(wù)鎖等基本功能的相關(guān)使用示例,需要的朋友可以參考下

介紹

IndexedDB是HTML5 WEB數(shù)據(jù)庫,允許HTML5 WEB應(yīng)用在用戶瀏覽器端存儲數(shù)據(jù)。對于應(yīng)用來說IndexedDB非常強大、有用,可以在客戶端的chrome,IE,Firefox等WEB瀏覽器中存儲大量數(shù)據(jù),下面簡單介紹一下IndexedDB的基本概念。

什么是IndexedDB

IndexedDB,HTML5新的數(shù)據(jù)存儲,可以在客戶端存儲、操作數(shù)據(jù),可以使應(yīng)用加載地更快,更好地響應(yīng)。它不同于關(guān)系型數(shù)據(jù)庫,擁有數(shù)據(jù)表、記錄。它影響著我們設(shè)計和創(chuàng)建應(yīng)用程序的方式。IndexedDB 創(chuàng)建有數(shù)據(jù)類型和簡單的JavaScript持久對象的object,每個object可以有索引,使其有效地查詢和遍歷整個集合。本文為您提供了如何在Web應(yīng)用程序中使用IndexedDB的真實例子。

開始

我們需要在執(zhí)行前包含下面前置代碼

JavaScript Code

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

//prefixes of window.IDB objects   

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

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

if (!indexedDB) {   

alert("Your browser doesn't support a stable version of IndexedDB.")   

}  

打開IndexedDB

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

JavaScript Code

var userData = [   

{ id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },   

{ id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }   

];  

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

JavaScript Code

var db;   

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

request.onerror = function(e) {   

console.log("error: ", e);   

};   

request.onsuccess = function(e) {   

db = request.result;   

console.log("success: "+ db);   

};   

request.onupgradeneeded = function(e) {   

}  

如上所示,我們已經(jīng)打開了名為"databaseName",指定版本號的數(shù)據(jù)庫,open()方法有兩個參數(shù):

1.第一個參數(shù)是數(shù)據(jù)庫名稱,它會檢測名稱為"databaseName"的數(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ù),而不是通過表。 每當(dāng)一個值存儲在對象存儲中,它與一個鍵相關(guān)聯(lián)。 它允許我們創(chuàng)建的任何對象存儲索引。 索引允許我們訪問存儲在對象存儲中的值。 下面的代碼顯示了如何創(chuàng)建對象存儲并插入預(yù)先準(zhǔn)備好的數(shù)據(jù):

JavaScript Code

request.onupgradeneeded = function(event) {   

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

for (var i in userData) {   

objectStore.add(userData[i]);    

}   

}  

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

手動將數(shù)據(jù)添加到表:

我們可以手動添加額外的數(shù)據(jù)到數(shù)據(jù)庫中。

JavaScript Code

function Add() {   

var request = db.transaction(["users"], "readwrite").objectStore("users")   

.add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });   

request.onsuccess = function(e) {   

alert("Gautam has been added to the database.");   

};   

request.onerror = function(e) {   

alert("Unable to add the information.");    

}   

}  

之前我們在數(shù)據(jù)庫中做任何的CRUD操作(讀,寫,修改),必須使用事務(wù)。 該transaction()方法是用來指定我們想要進行事務(wù)處理的對象存儲。 transaction()方法接受3個參數(shù)(第二個和第三個是可選的)。 第一個是我們要處理的對象存儲的列表,第二個指定我們是否要只讀/讀寫,第三個是版本變化。

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

get()方法用于從對象存儲中檢索數(shù)據(jù)。 我們之前已經(jīng)設(shè)置對象的id作為的keyPath,所以get()方法將查找具有相同id值的對象。 下面的代碼將返回我們命名為“Bidulata”的對象:

JavaScript Code

function Read() {   

var objectStore = db.transaction(["users"]).objectStore("users");   

var request = objectStore.get("2");   

request.onerror = function(event) {   

alert("Unable to retrieve data from database!");   

};   

request.onsuccess = function(event) {    

if(request.result) {   

alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);   

} else {   

alert("Bidulata couldn't be found in your database!");    

}   

};   

}  

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

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

JavaScript Code

function ReadAll() {   

var objectStore = db.transaction("users").objectStore("users");    

var req = objectStore.openCursor();   

req.onsuccess = function(event) {   

db.close();   

var res = event.target.result;   

if (res) {   

alert("Key " + res.key + " is " + res.value.name + ", Age: " + res.value.age + ", Email: " + res.value.email);   

res.continue();   

}   

};   

req.onerror = function (e) {   

console.log("Error Getting: ", e);   

};    

}  

該openCursor()用于遍歷數(shù)據(jù)庫中的多個記錄。 在continue()函數(shù)中繼續(xù)讀取下一條記錄。

刪除表中的記錄

下面的方法從對象中刪除記錄。

JavaScript Code

function Remove() {    

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

request.onsuccess = function(event) {   

alert("Tapas's entry has been removed from your database.");   

};   

}  

我們要將對象的keyPath作為參數(shù)傳遞給delete()方法。

最終代碼

下面的方法從對象源中刪除一條記錄:

JavaScript Code

<!DOCTYPE html>  

<head>  

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

<title>IndexedDB</title>  

<script type="text/javascript">  

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

//prefixes of window.IDB objects   

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

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

if (!indexedDB) {   

alert("Your browser doesn't support a stable version of IndexedDB.")   

}   

var customerData = [   

{ id: "1", name: "Tapas", age: 33, email: "tapas@example.com" },   

{ id: "2", name: "Bidulata", age: 55, email: "bidu@home.com" }   

];   

var db;   

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

request.onerror = function(e) {   

console.log("error: ", e);   

};   

request.onsuccess = function(e) {   

db = request.result;   

console.log("success: "+ db);   

};   

request.onupgradeneeded = function(event) {   

}   

request.onupgradeneeded = function(event) {   

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

for (var i in userData) {   

objectStore.add(userData[i]);    

}   

}   

function Add() {   

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

.objectStore("users")   

.add({ id: "3", name: "Gautam", age: 30, email: "gautam@store.org" });   

request.onsuccess = function(e) {   

alert("Gautam has been added to the database.");   

};   

request.onerror = function(e) {   

alert("Unable to add the information.");    

}   

}   

function Read() {   

var objectStore = db.transaction("users").objectStore("users");   

var request = objectStore.get("2");   

request.onerror = function(event) {   

alert("Unable to retrieve data from database!");   

};   

request.onsuccess = function(event) {    

if(request.result) {   

alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);   

} else {   

alert("Bidulata couldn't be found in your database!");    

}   

};   

}   

function ReadAll() {   

var objectStore = db.transaction("users").objectStore("users");    

var req = objectStore.openCursor();   

req.onsuccess = function(event) {   

db.close();   

var res = event.target.result;   

if (res) {   

alert("Key " + res.key + " is " + res.value.name + ", Age: " + res.value.age + ", Email: " + res.value.email);   

res.continue();   

}   

};   

req.onerror = function (e) {   

console.log("Error Getting: ", e);   

};    

}   

function Remove() {    

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

request.onsuccess = function(event) {   

alert("Tapas's entry has been removed from your database.");   

};   

}   

</script>  

</head>  

<body>  

<button onclick="Add()">Add record</button>  

<button onclick="Remove()">Delete record</button>  

<button onclick="Read()">Retrieve single record</button>  

<button onclick="ReadAll()">Retrieve all records</button>  

</body>  

</html>  

localStorage是不帶lock功能的。那么要實現(xiàn)前端的數(shù)據(jù)共享并且需要lock功能那就需要使用其它本儲存方式,比如indexedDB。indededDB使用的是事務(wù)處理的機制,那實際上就是lock功能。

做這個測試需要先簡單的封裝下indexedDB的操作,因為indexedDB的連接比較麻煩,而且兩個測試頁面都需要用到

JavaScript Code

//db.js   

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

IDBDatabase.prototype.doTransaction=function(f){   

  f(this.transaction(["Obj"],"readwrite").objectStore("Obj"));   

};   

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

(function(){   

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

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

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

  cn.onupgradeneeded=function(e){   

    e.target.result.createObjectStore("Obj");   

  };   

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

  cn.onsuccess=function(e){   

    main(e.target.result);   

  };   

})();   

接著是兩個測試頁面   

<script src="db.js"></script>  

<script>  

//a.html   

function main(e){   

  (function callee(){   

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

    e.doTransaction(function(e){   

      e.put(1,"test"); //設(shè)置test的值為1   

      e.put(2,"test"); //設(shè)置test的值為2   

    });   

    setTimeout(callee);   

  })();   

};   

</script>  

<script src="db.js"></script>  

<script>  

//b.html   

function main(e){   

  (function callee(){   

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

    e.doTransaction(function(e){   

      //獲取test的值   

      e.get("test").onsuccess=function(e){   

        console.log(e.target.result);   

      };   

    });   

    setTimeout(callee);   

  })();   

};   

</script>  

把localStorage換成了indexedDB事務(wù)處理。但是結(jié)果就不同

名單

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

更多信息請查看網(wǎng)頁制作
易賢網(wǎng)手機網(wǎng)站地址:深入解析HTML5的IndexedDB索引數(shù)據(jù)庫
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報警專用圖標(biāo)