indexedDB 是 HTML5 提供的一種本地存儲,通常用戶保存大量用戶數據並要求數據之間有搜索須要的場景,當網絡斷開的時候,能夠作一些離線應用,它比 SQL 方便,不用去寫一些特定的語句對數據進行操做,數據格式爲 json。web
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var request = indexedDB.open(databasename, version);
request.onerror = function(e){
// 建立失敗回調函數
};
request.onsuccess = function(e){
// 建立成功回調函數
};
request.onupgradeneededd = function(e){
// 當數據庫改變是回調函數
};
複製代碼
注意這裏的版本號只能夠是整數數據庫
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("name", { keyPath: "id" });
};
複製代碼
// 增
addData:function(db,storename,data){
var store = store = db.transaction(storename,'readwrite').objectStore(storename),request;
for(var i = 0 ; i < data.length;i++){
request = store.add(data[i]);
request.onerror = function(){
console.error('add添加數據庫中已有該數據')
};
request.onsuccess = function(){
console.log('add添加數據已存入數據庫')
};
}
}
複製代碼
添加數據,重複添加會報錯json
// 刪
deleteData:function(db,storename,key){
var store = store = db.transaction(storename,'readwrite').objectStore(storename);
store.delete(key)
console.log('已刪除存儲空間'+storename+'中'+key+'記錄');
}
複製代碼
// 改
putData:function(db,storename,data){
var store = store = db.transaction(storename,'readwrite').objectStore(storename),request;
for(var i = 0 ; i < data.length;i++){
request = store.put(data[i]);
request.onerror = function(){
console.error('put添加數據庫中已有該數據')
};
request.onsuccess = function(){
console.log('put添加數據已存入數據庫')
};
}
}
複製代碼
重複添加已經存在的數據會更新原有數據瀏覽器
// 查
getDataByKey:function(db,storename,key){
var store = db.transaction(storename,'readwrite').objectStore(storename);
var request = store.get(key);
request.onerror = function(){
console.error('getDataByKey error');
};
request.onsuccess = function(e){
var result = e.target.result;
console.log('查找數據成功')
console.log(result);
};
}
複製代碼
根據存儲空間的鍵找到對應數據,本例爲 id緩存
db.close();
複製代碼
掌握了使用步驟以後,咱們來結合它的優、缺點談談其使用場景。bash
參考: indexedDB API網絡