日期:2014-05-16  浏览次数:20434 次

IndexedDB学习二:使用
目标
  • 打开数据库连接,开始一个事物
  • 创建存储对象
  • 请求数据库操作:比如添加或查询数据。
  • 等待操作完成, 监听正确的DOM事件。
  • 对结果进行其它操作。


创建和构建数据存储
  • 使用一个稳定版本的IndexedDB
  • // In the following line, you should include the prefixes of implementations you want to test.
    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    // DON'T use "var indexedDB = ..." if you're not in a function.
    // Moreover, you may need references to some window.IDB* objects:
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
    // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
    if (!window.indexedDB) {
        window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.")
    }
    
  • 打开数据库
  • // Let us open our database
    var request = window.indexedDB.open("MyTestDatabase");
    // open a database with version number
    var request = indexedDB.open("MyTestDatabase", 3);
    

    处理机制
    var db;
    var request = indexedDB.open("MyTestDatabase");
    request.onerror = function(event) {
      // Do something with request.errorCode!
    };
    request.onsuccess = function(event) {
      // Do something with request.result!
      db = request.result;
    };
    

    处理错误
    db.onerror = function(event) {
      // Generic error handler for all errors targeted at this database's
      // requests!
      alert("Database error: " + event.target.errorCode);
    };
    
  • 创建和更新数据库版本
  • // This event is only implemented in recent browsers
    request.onupgradeneeded = function(event) { 
       // Update object stores and indices .... 
    };
    
  • 构建数据库
  • IndexedDB 使用对象存储空间而不是表,并且一个单独的数据库可以包含任意数量的对象存储空间。每当一个值被存储进一个对象存储空间时,它会被和一个键相关联。键的提供可以有几种不同的方法,这取决于对象存储空间是使用 key path 还是 key generator。

    事务可以接收三种不同类型的 DOM 事件: error,abort,以及 complete。如果在 error 事件上通过调用 preventDefault() 处理了这个错误,整个事务被回滚了。如果在事务中调用 abort(),那么事务被回滚并且有关事物的一个 abort 事件被触发。
    // This is what our customer data looks like.
    const customerData = [
      { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
      { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
    ];
    const dbName = "the_name";
    
    var request = indexedDB.open(dbName, 2);
     
    request.onerror = function(event) {
      // Handle errors.
    };
    request.onupgradeneeded = function(event) {
      var db = event.target.result;
     
      // Create an objectStore to hold information about our customers. We're
      // going to use "ssn" as our key path because it's guaranteed to be
      // unique.
      var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
     
      // Create an index to search customers by name. We may have duplicates
      // so we can't use a unique index.
      objectStore.createIndex("name", "name", { unique: false });
     
      // Create an index to search customers by email. We want to ensure that
      // no two customers have the same email, so use a unique index.
      objectStore.createIndex("email", "email", { unique: true });
     
      // Store values in the newly created objectStore.
      for (var i in customerData) {
        objectStore.add(customerData[i]);
      }
    };
    

    onupgradeneeded是修改数据结构的唯一方法。
    createObjectStore是创建数据对象的方法。例子中可以通过SSN获取存储对象。
  • 添加和删除数据
  • // adding data
    var transaction = db.transaction(["customers"], "readwrite");
    transaction.oncomplete = function(event) {
      alert("All done!");
    };
     
    transaction.onerror = function(event) {
      // Don't forget to handle errors!
    };
     
    var objectStore = transaction.objectStore("customers");
    for (var i in customerData) {
      var request = objectStore.add(customerData[i]);
      requ