IndexedDB為了在客戶(hù)端存儲(chǔ)大量的結(jié)構(gòu)化數(shù)據(jù),并且使用索引高效檢索的API。
# 簡(jiǎn)單使用
var request=window.indexedDB.open('jaxi',1); //打開(kāi)或創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)
request.onerror=function(e){//打開(kāi)數(shù)據(jù)庫(kù)錯(cuò)誤時(shí)執(zhí)行
console.log(e.currentTarget.error.message);
}
request.onsuccess=function(e){//打開(kāi)數(shù)據(jù)庫(kù)正確時(shí)執(zhí)行
myDB=e.target.result;
//表添加數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
t.add({id:1004,name:'jaxi',age:'12'})
//表刪除數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
t.delete(1001);
//表更改數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
t.put({id:1007,name:'jaxxi',age:'95'});
//表查詢(xún)數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
t.get(1001);
}
request.onupgradeneeded=function(e){//打開(kāi)數(shù)據(jù)庫(kù)版本檢測(cè)(也可用來(lái)添加表)
var db=e.target.result;
if(!db.objectStoreNames.contains('students')){
db.createObjectStore('students',{keyPath:'id'});
}
}
# 解釋:
1.db.objectStoreNames.contains('students');//數(shù)據(jù)庫(kù)中是否包含這個(gè)表
2.db.createObjectStore('students',{keyPath:'id'});//數(shù)據(jù)庫(kù)創(chuàng)建一個(gè)表并指定id
3.myDB.transaction('students','readwrite').objectStore('students');
//表事務(wù)(表名,'操作方式').objectStore('預(yù)操作表')
4.t.add();表添加數(shù)據(jù) t.put();表更新數(shù)據(jù)
5.t.delete('字段值');表刪除數(shù)據(jù) t.get();表查詢(xún)數(shù)據(jù)
6.db.close();關(guān)閉數(shù)據(jù)庫(kù)
7.indexedDB.deleteDatabase(‘dbName’);刪除數(shù)據(jù)庫(kù)
# 利用游標(biāo)和索引來(lái)獲取數(shù)據(jù)
同上一樣(在數(shù)據(jù)庫(kù)版本檢測(cè)時(shí)睛榄,需要?jiǎng)?chuàng)建索引)
request.onupgradeneeded=function(e){//打開(kāi)數(shù)據(jù)庫(kù)版本檢測(cè)(也可用來(lái)添加表)
var db=e.target.result;
if(!db.objectStoreNames.contains('students')){
var store=db.createObjectStore('students',{keyPath:'id'});
store.createIndex('nameIndex','name',{unique:true});
//創(chuàng)建索引store.createIndex('索引名稱(chēng)','索引屬性名',{unique:true}索引屬性值是否唯一);
store.createIndex('ageIndex','age',{unique:false});
}
}
//利用游標(biāo)查詢(xún)表數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
var reques=t.openCursor();//新建一個(gè)游標(biāo)
reques.onsuccess=function(e){
var cursor=e.target.result;
if(cursor){
var currentStudent=cursor.value;
console.log('Key:'+cursor.key+" Value:"+currentStudent.name);
cursor.continue();//游標(biāo)下移,沒(méi)有返回undefined
}
};
//游標(biāo)與索引結(jié)合查詢(xún)表數(shù)據(jù)
var t=myDB.transaction('students','readwrite').objectStore('students');
var index=t.index('ageIndex');//指定索引
var reques=index.openCursor(IDBKeyRange.only(26));
//新建一個(gè)游標(biāo) 指定是26歲
reques.onsuccess=function(e){
var cursor=e.target.result;
if(cursor){
var currentStudent=cursor.value;
console.log('Key:'+cursor.key+" Value:"+currentStudent.name);
}
};