zoukankan      html  css  js  c++  java
  • win8: IndexedDB

    应用开发少不了数据永久性存储,Win8上有多种存储方式( http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx ),本地的,漫游的,临时的设置存储及数据存储,不同场景适用不同的存储方式。IndexedDB适用于存储那些较大的、需要索引查找的数据。

    有关IndexedDB的基本概念及详细介绍,可以参照:

    https://developer.mozilla.org/zh-CN/docs/IndexedDB/Basic_Concepts_Behind_IndexedDB

    https://developer.mozilla.org/zh-CN/docs/IndexedDB/Using_IndexedDB

    使用之前应注意一些基本概念:

    1、IndexedDB 数据库使用key-value键值对储存数据. values 数据可以是非常复杂的结构体. 属于key-value数据库(不是关系型数据库,nosql的)。

    2、IndexedDB 是事务模式的数据库.任何操作都发生在事务(transaction)中,操作通过请求在事物中进行。

    3、The IndexedDB API 基本上是异步的

    4、IndexedDB 是面向对象的。

    5、IndexedDB uses requests all over the place

    6、IndexedDB uses DOM events to notify you when results are available。 结果通常是success or error。

    使用基本模式:

    1. 打开数据库并且开始一个事务。
    2. 创建一个 object store。
    3. 构建一个请求来执行一些数据库操作,像增加或提取数据等。
    4. 通过监听正确类型的 DOM 事件以等待操作完成。
    5. 在操作结果上进行一些操作(可以在 request 对象中找到)

    object store 就是我们说的键值对,即是我们存储的操作对象。indexedDB中没有表的概念,我们数据的存储对象就是object store。

    打开数据库:

    varrequest = window.indexedDB.open("MyTestDatabase");

    varrequest = indexedDB.open("MyTestDatabase", 3);//3为版本号,一般都是整数

    打开一个数据库也是一个请求的操作,请求或成功或失败,都会有回调函数进行相关的处理:

    request.onerror = function(event) {
      // Do something with request.errorCode!
    };
    request.onsuccess = function(event) {
      // Do something with request.result!
    };

    Mozilla有个例子:

    // 我们的客户数据看起来像这样。
    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) {
      // 错误处理程序在这里。
    };
    request.onupgradeneeded = function(event) {
      var db = event.target.result;
     
      // 创建一个对象存储空间来持有有关我们客户的信息。
      // 我们将使用 "ssn" 作为我们的 key path 因为它保证是唯一的。
      var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
     
      // 创建一个索引来通过 name 搜索客户。
      // 可能会有重复的,因此我们不能使用 unique 索引。
      objectStore.createIndex("name", "name", { unique: false });
     
      // 创建一个索引来通过 email 搜索客户。
      // 我们希望确保不会有两个客户使用相同的 email 地址,因此我们使用一个 unique 索引。
      objectStore.createIndex("email", "email", { unique: true });
     
      // 在新创建的对象存储空间中保存值
      for (var i in customerData) {
        objectStore.add(customerData[i]);
      }
    };

    这样算是创建了数据库及objectStore

    以后我们要进行数据的增删改查时一般是通过transaction,请求去操作。

    var transaction = db.transaction(["customers"], "readwrite");
    
    var objectStore = transaction.objectStore("customers");

    再通过objectStore的add、delete、put 进行数据的增加、删除、更改的操作。

    最后你也可以使用游标的操作,来更方便的管理数据,具体可以看上面给出的Mozilla的链接。

    贴出Win8 modern中使用IndexedDB的具体实现:

        function startReadData() {
            var dbRequest = window.indexedDB.open("eBookDB", 1);
    
            dbRequest.onerror = function () { console.log("Error "); };
            dbRequest.onblocked = function () { console.log("Database access blocked."); };
            dbRequest.onupgradeneeded = function (evt) { console.log("read note upgrade"); if (ebookWin8.db) { ebookWin8.db.close(); } };
            dbRequest.onsuccess = function (evt) { dbSuccess(evt); };
        }
        function dbSuccess(evt) {
    
            if (ebookWin8.db) {
                ebookWin8.db.close();
            }
            ebookWin8.db = evt.target.result;
            if (ebookWin8.db.objectStoreNames.length === 0) {
                console.log("Database schema does not exist. ");
                ebookWin8.db.close();
                ebookWin8.db = null;
                window.indexedDB.deleteDatabase("eBookDB", 1);
            } else {
                readData(evt);
            }
        }
        function readData(evt) {
            
            NoteList = [];
    
            // Open our database tables.
            var txn = ebookWin8.db.transaction(["notes"], "readwrite");
            txn.oncomplete = function () {
                bindListData();
                console.log("read data . note complete");
            };
            txn.onerror = function () {
                console.log("note error");
            };
            txn.onabort = function () {
                console.log("note abort");
            };
    
            var ebookCursorRequest = txn.objectStore("notes").openCursor();
    
            ebookCursorRequest.onsuccess = function (e) {
                var cursor = e.target.result;
                if (cursor) {
                    console.log(cursor.value.id);
                    NoteList.push(cursor.value);
                    cursor.continue();
                }
            };
            
        }
        function AddNewNote(newNote) {
    
            if (ebookWin8.db === null) {
                console.log("Data has not been read yet");
                return;
            }
         
            var txn = ebookWin8.db.transaction(["notes"], "readwrite");
    
            txn.onerror = function (evt) { console.log("Error writing data"); };
            txn.onabort = function (evt) { console.log("Writing of data aborted"); };
            txn.oncomplete = function () {
                console.log("Changes saved to database");
                readData();
            };
    
            var notesStore = txn.objectStore("notes");
    
            var addResult = notesStore.add({ note: newNote });
    
            addResult.onerror = function (evt) {
                console.log("Error adding data");
            };
    
        }
        function DeleteNote(id) {
            // If the database has not been opened, log an error.
            if (ebookWin8.db === null) {
                console.log("Data has not been read yet");
                return;
            }
    
            // Create a transaction to write the changes to the database        
            var txn = ebookWin8.db.transaction(["notes"], "readwrite");
    
            // Set the event callbacks for the transaction
            txn.onerror = function (evt) { console.log("Error writing data"); };
            txn.onabort = function (evt) { console.log("Writing of data aborted"); };
            txn.oncomplete = function () {
                console.log("Changes saved to database");
            };
    
            var notesStore = txn.objectStore("notes");
    
            var Result = notesStore.delete(id);
    
            Result.onerror = function (evt) {
                console.log("Error adding data");
            };
        }
        function ChangeNote(id, newNote) {
            if (ebookWin8.db === null) {
                console.log("Data has not been read yet");
                return;
            }
            
            var txn = ebookWin8.db.transaction(["notes"], "readwrite");
    
            txn.onerror = function (evt) { console.log("Error writing data"); };
            txn.onabort = function (evt) { console.log("Writing of data aborted"); };
            txn.oncomplete = function () {
                console.log("Changes saved to database");
                readData();
            };
    
            var notesStore = txn.objectStore("notes");
    
            var addResult = notesStore.put({ id:id, note: newNote });
    
            addResult.onerror = function (evt) {
                console.log("Error adding data");
            };
        }

     代码是根据我具体项目的实现,需要整个的程序的当然推荐看官方的Sample Code。

    http://code.msdn.microsoft.com/windowsapps/IndexedDB-sample-eb1e95af

       


    作者:老Zhan
    出处:http://www.cnblogs.com/mybkn/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

     
  • 相关阅读:
    ICONS-图标库
    图形资源
    vue项目中,如果修改了组件名称,vscode编辑器会在引入修改组件的名字处提示红色波浪线 The file is in the program because:Imported via xxx Root file specified for compilation .
    接口在dev环境报跨域问题(has been blocked by CORS policy:Response to preflight request doesn't pass access control check:No 'Access-Control-Allow-Origin' header ispresent on the requested resource.),qa环境正常
    阿里云occ的图片文件URL用浏览器直接打开无法访问,提示This XML file does noe appear to have any style information associated with it. The document tree is shown below.
    vue 项目使用element ui 中tree组件 check-strictly 用法(父子不互相关联的反显情况)
    高德地图进行线路规划绘制标记点操作(vue)
    vue中实现拖拽调整顺序功能
    2021-01-22 浏览器相关知识
    2021-01-22 js 相关知识点
  • 原文地址:https://www.cnblogs.com/mybkn/p/2994010.html
Copyright © 2011-2022 走看看