來源:sunqy1995 發(fā)布時間:2019-03-28 14:11:21 閱讀量:1553
簡介
前端從發(fā)展到現(xiàn)在已經(jīng)形成了一定的瀏覽器存儲數(shù)據(jù)的方式,有cookie、sessionStorage、localStorage、indexedDB以及被廢棄的web sql.
特點:
鍵值對存儲 每一條數(shù)據(jù)有一個主鍵,主鍵獨一無二,實行key-value進行存儲。
異步操作 實行異步操作。
支持事務 支持事務操作意味著數(shù)據(jù)操作只有成功和失敗兩種狀態(tài)。
同源策略 每一個數(shù)據(jù)庫對應創(chuàng)建它的域名,只能訪問自身域名下的數(shù)據(jù)庫。
存儲空間大 支持大于250M的數(shù)據(jù),甚至沒有上限
支持二進制存儲 可以存儲二進制數(shù)據(jù)。
數(shù)據(jù)庫操作
數(shù)據(jù)庫連接與創(chuàng)建數(shù)據(jù)庫
使用window對象indexedDB屬性的open()方法,其中第一個參數(shù)是數(shù)據(jù)庫名稱,如果存在就打開數(shù)據(jù)庫不存在就創(chuàng)建。第二個參數(shù)是數(shù)據(jù)庫的版本是大于0的正整數(shù)。
數(shù)據(jù)庫打開時,會觸發(fā)4中事件:
success: 打開成功。
error: 打開失敗
upgradeneeded: 第一次打開該數(shù)據(jù)庫,或者數(shù)據(jù)庫版本發(fā)生變化時觸發(fā)。
blocked: 上一次的數(shù)據(jù)庫連接還未關(guān)閉
注意:第一次打開數(shù)據(jù)庫時,會先觸發(fā)upgradeneeded事件,然后觸發(fā)success事件。
let request = indexedDB.open(name, 1);
request.onsuccess = function(e){
db = e.target.result;
}
創(chuàng)建"對象倉庫"
使用createObjectStore()進行對象倉庫的創(chuàng)建。
第一個參數(shù)是倉庫名稱,同一個數(shù)據(jù)庫中不可以重復。
第二個參數(shù)是一個對象,包含keyPath和autoIncrement,分別表示每條記錄的鍵名和是否使用自動遞增的整數(shù)作為鍵名,默認為false
db.createObjectStore(name[,options]);
//一般創(chuàng)建倉庫都在upgradeneeded事件中
request.addEventListener('upgradeneeded', e => {
db = e.target.result;
if(!db.objectStoreNames.contains('person')){
let store = db.createObjectStore(table, {keyPath: 'keyword', autoIncrement: false});
}
事務的操作
indexedDB支持事務操作,事務就是說在對數(shù)據(jù)庫的操作只有成功和失敗這兩種可能,所以說在進行數(shù)據(jù)庫的操作之前需要先創(chuàng)建事務。
name是要操作的倉庫的名稱
readwrite是對倉庫進行什么操作
const tx = db.transaction(name, 'readwrite');
1
新增操作
indexedDB數(shù)據(jù)庫也可以進行添加數(shù)據(jù)的操作,需要先添加事務,使用add進行添加,但是如果是相同的就會操作失敗。還可以使用鏈式調(diào)用,indexedDB操作時異步操作,所以需要進行監(jiān)聽事件監(jiān)聽成功和失敗。
const tx = db.transaction('name', 'readwrite');
const store = tx.objectStore('name');
const add = store.add({keyword:'table',s:0});
add.addEventListener('success', e => {
console.log('操作成功');
})
add.addEventListener('error', e => {
console.log('操作失敗');
})
更新數(shù)據(jù)
如果想添加相同的數(shù)據(jù)可以使用put方法
const tx = db.transaction('name', 'readwrite');
const store = tx.objectStore('name');
const add = store.put({keyword:'table',s:0});
add.addEventListener('success', e => {
console.log('操作成功');
})
add.addEventListener('error', e => {
console.log('操作失敗');
})
獲取數(shù)據(jù)
使用get方法,通過key值獲得該值。
const get = db.transaction('name','readwrite')
.objectStore('name')
.get('keyword');
刪除數(shù)據(jù)
使用delete方法,通過key值進行刪除
const get = db.transaction('name','readwrite')
.objectStore('name')
.delete('keyword');
游標的使用
indexedDB有一種游標操作,從倉庫的第一條開始一直遍歷到最后一條,使用openCursor創(chuàng)建,使用continue,result就是倉庫中的所有數(shù)據(jù)。
const cursor = db.transaction('users').objectStore('users').openCursor();
cursor.addEventListener('success',e=>{
let result = e.target.result;
if(result){
console.log('cursor',result);
cursor.continue();//可以將地址指針指向下一個地址。
}else{
console.log('遍歷完成',result);
}
})