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/archive/2013/04/01/2994010.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值