JS--IndexedDB(非全面指南)

一、 基本概念(中文版)
二、名詞解釋(中文版)
三、 IDBFactory對象(等價window.indexedDB)
  • open(name,version): 返回IDBOpenDBRequest對象,
  • cmp(value1,value2):將兩個值作為鍵進行比較,以確定IndexedDB操作的相等性和排序,例如存儲和迭代。返回值 -1為< 0為= 1為>
  • delete?Database() 返回IDBOpenDBRequest對象
var DBDeleteRequest = window.indexedDB.deleteDatabase("toDoList");

DBDeleteRequest.onerror = function(event) {
  console.log("Error deleting database.");
};
 
DBDeleteRequest.onsuccess = function(event) {
  console.log("Database deleted successfully");
    
  console.log(event.result); // should be undefined
};
四、IDBOpenDBRequest 接口

blocked事件
upgradeneeded事件

var db;

var request = window.indexedDB.open("library", 3);

request.onupgradeneeded = function(event) {
  db = request.result;
 
  db.onerror = function(errorEvent) {
    note.innerHTML += '<li>Error loading database.</li>';
  };

  if (event.oldVersion < 1) {
   
    var store = db.createObjectStore("books", {keyPath: "isbn"});
    var titleIndex = store.createIndex("by_title", "title", {unique: true});
    var authorIndex = store.createIndex("by_author", "author");
  }
  if (event.oldVersion < 2) {
   
    var bookStore = request.transaction.objectStore("books");
    var yearIndex = bookStore.createIndex("by_year", "year");
  }
  if (event.oldVersion < 3) {
    var magazines = db.createObjectStore("magazines");
    var publisherIndex = magazines.createIndex("by_publisher", "publisher");
    var frequencyIndex = magazines.createIndex("by_frequency", "frequency");
  }
};

request.onerror = function(event) {
  console.log(event)
};

request.onsuccess = function(event) {
  db = request.result;
};
五、 IDBDatabase對象
  • 事件 :
    • abort:在中斷數(shù)據(jù)庫訪問時觸發(fā)
    • error:當訪問數(shù)據(jù)庫失敗時觸發(fā)。
    • versionchange:當數(shù)據(jù)庫結構發(fā)生更改時觸發(fā) close
  • 屬性 :
    • name :當前連接數(shù)據(jù)庫名
    • version:當前連接數(shù)據(jù)庫的版本
    • objectStoreNames:當前連接連接數(shù)據(jù)庫中所有的object store 名字列表
  • 方法 :
    • close() :在一個單獨的線程中關閉數(shù)據(jù)庫連接并立即返回。
    • create?Object?Store():創(chuàng)建并返回一個新的 object store 或 index
    • delete?Object?Store():此方法只能在 versionchange 事務中被調用。
    • transaction(storeNames,mode):開啟一個事務
   // 鍵生成器和keyPath
    var objectStore = db.createObjectStore("names", { autoIncrement : true }); //鍵生成器
    var objectStore = db.createObjectStore("customers", { keyPath: "ssn" }); //keyPath
    var objectStore = db.createObjectStore("names", { keyPath: 'id', autoIncrement: true });
六、IDBTransacation對象(事務)
  • 事務提供了三種模式:readonly、readwriteversionchange。
  • 事務接收三種不同的 DOM 事件:errorabortcomplete。
  • 事件:upgradeneeded``complete``abort``success``error``blocked``versionchange``close
  • 屬性:db error mode object?Store?Names
  • 方法:abort() object?Store()
  // 開啟一個事務
  var transaction = db.transaction(["customers"], "readwrite");
  • transaction() 方法接受兩個參數(shù)(一個是可選的)并返回一個事務對象。第一個參數(shù)是事務希望跨越的對象存儲空間的列表。如果你希望事務能夠跨越所有的對象存儲空間你可以傳入一個空數(shù)組。如果你沒有為第二個參數(shù)指定任何內容,你得到的是只讀事務。如果你想寫入數(shù)據(jù),你需要傳入 "readwrite" 標識。
  • 事務方法返回一個包含IDBIndex.objectStore方法的事務對象,使用 IDBIndex.objectStore你可以訪問你的對象倉庫。
五、IDBObjectStore對象
  • 屬性 : auto?Increment index?Names key?Path name transaction
  • 事件 upgradeneeded complete abort success error blocked versionchange close
方法 參數(shù) 返回 描述
add() value[, key] IDBRequest add方法只能插入數(shù)據(jù)。
clear () IDBRequest
getAll() [A key or IDBKeyRange[,在找到多個值時要返回的值的數(shù)量] IDBRequest
getAllKeys() 同上 IDBRequest
count() 參數(shù)可以是鍵,或鍵范圍(key range) IDBRequest
createIndex() (in DOMString name, in DOMString keyPath, in optional boolean unique) IDBIndex 該方法只能從versionchange事務模式的回調方法中被調用。
delete 參數(shù)可以是鍵,或鍵范圍(key range) IDBRequest
deleteIndex (in any DOMString indexName) void 該方法只能從versionchange事務模式的回調方法中被調用。
get (in any key) IDBRequest 不存在時就像存在記錄時一樣,但具有undefined值。
index (in DOMString name) IDBIndex
openCursor (in optional IDBKeyRange range, in optional unsigned short direction) IDBRequest
put (in any value, in optional any key) IDBRequest put方法是更新或插入方法。
六、IDBRequest接口
六、IDBIndex對象
六、IDBCursor對象(游標)

屬性 direction key primaryKey source

// 首先,確定你已經(jīng)在 request.onupgradeneeded 中創(chuàng)建了索引:
// objectStore.createIndex("name", "name",{ unique: false });
// 否則你將得到 DOMException。

var index = objectStore.index("name");

index.get("Donna").onsuccess = function(event) {
  alert("Donna's SSN is " + event.target.result.ssn);
};
  • “name” 游標不是唯一的,因此 name 被設成 "Donna" 的記錄可能不止一條。在這種情況下,你總是得到鍵值最小的那個。

  • 如果你需要訪問帶有給定 name 的所有的記錄你可以使用一個游標。你可以在索引上打開兩個不同類型的游標。

    • 一個常規(guī)游標映射索引屬性到對象存儲空間中的對象。
    • 一個鍵索引映射索引屬性到用來存儲對象存儲空間中的對象的鍵。不同之處被展示如下:
index.openCursor().onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // cursor.key 是一個 name, 就像 "Bill", 然后 cursor.value 是整個對象。
    alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
    cursor.continue();
  }
};

index.openKeyCursor().onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // cursor.key 是一個 name, 就像 "Bill", 然后 cursor.value 是那個 SSN。
    // 沒有辦法可以得到存儲對象的其余部分。
    alert("Name: " + cursor.key + ", SSN: " + cursor.value);
    cursor.continue();
  }
};
六、IDBKeyRange對象(指定游標的范圍和方向)
  • 屬性 lower lower?Open upper upper?Open
  • 方法 bound() includes() lower?Bound() only() upper?Bound()
// 僅匹配 "Donna"
var singleKeyRange = IDBKeyRange.only("Donna");

// 匹配所有超過“Bill”的,包括“Bill”
var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");

// 匹配所有超過“Bill”的,但不包括“Bill”
var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);

// 匹配所有不超過“Donna”的,但不包括“Donna”
var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);

// 匹配所有在“Bill”和“Donna”之間的,但不包括“Donna”
var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);

// 使用其中的一個鍵范圍,把它作為 openCursor()/openKeyCursor 的第一個參數(shù)
index.openCursor(boundKeyRange).onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // 當匹配時進行一些操作
    cursor.continue();
  }
};
  • 有時候你可能想要以倒序而不是正序(所有游標的默認順序)來遍歷。切換方向是通過傳遞 prev 到 openCursor() 方法來實現(xiàn)的:
objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // 進行一些操作
    cursor.continue();
  }
};
  • 如果你只是想改變遍歷的方向,而不想對結果進行篩選,你只需要給第一個參數(shù)傳入 null。
index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) {
  var cursor = event.target.result;
  if (cursor) {
    // Do something with the entries.
    cursor.continue();
  }
};
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容