Firefox OS中使用IndexedDB

移动开发
截至到现在IndexedDB,不同的厂商提供的调用方式可能会有所差异。本文针对firefox os,对IndexedDB的常用的使用进行说明。本文的示例在firefox os和firfox浏览器进行过测试。其他浏览器的使用请根据相关API文档进行修改。

截至到现在IndexedDB,不同的厂商提供的调用方式可能会有所差异。本文针对firefox os,对IndexedDB的常用的使用进行说明。本文的示例在firefox os和firfox浏览器进行过测试。其他浏览器的使用请根据相关API文档进行修改。

IndexedDB是存储和快速检索结构型数据的客户端API,数据采用key/value的形式,value可以是结构型的数据对象,如json对象。

一、打开一个数据库

  1. //Open IndexedDB
  2. function openDB() {
  3.   var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
  4.   var request = indexedDB.open("B2GDBTest", 1);
  5.   request.onsuccess = function(event) {
  6.     console.log("database open success:" + request.result);
  7.     db = request.result;
  8.   };
  9.   request.onupgradeneeded = function(event) {
  10.    createObjectStore(event.target.result);
  11.   };
  12.   request.onerror = function(event) {
  13.    console.log("database open error:" + request.errorCode);
  14.   };
  15. }

首先需要获取一个IDBFactory对象,目前不同的浏览器获取的方法有所不同,可以使用下面的写法来兼容不同的浏览器(本文的DEMO只针对firefox os或者firefox浏览器)

  1. var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; 

使用IDBFactory

  1. IDBOpenDBRequest open (in DOMString name, long long version); 

打开数据库的时候需要指定数据库的名字和版本,并按照如下的顺序执行打开操作

1.如果数据库已经存在,会等到versionchange事物结束后继续执行,如果打开了一个待删除的数据库,会等待删除操作完毕后继续执行。(注意:这两个事件并不是本次open数据库产生的,而是其他的操作中产生的未完成的versionchange和删除操作)

2.如果打开的数据库的版本小于已经存在的数据库版本,或终止执行,并返回一个类型为VersionError的DOMError

3.如果打开的数据库版本大于已经存在的数据库版本,会执行versionchange事物,并执行onupgradeneeded回调函数

4.如果打开的数据库不存在,会创建一个版本为1没有任何ObjectStore新的数据库

5.连接打开的数据库

二、创建一个ObjectStore

ObjectStore相当与关系型数据库里的表,你只能在versionchange事物中创建或者删除ObjectStore,而现在,你只能在上面提到的onupgradeneeded回调中创建或删除ObjectStore。创建ObjectStore的操作可以参考如下代码

  1. //Create Object Store  
  2. function createObjectStore(db) {  
  3.   if (!db) {  
  4.     alert("Database is not open!");  
  5.     return;  
  6.   }  
  7.   if (db.version == 1) {  
  8.  
  9.     if (db.objectStoreNames.contains('customers')) {  
  10.       db.deleteObjectStore("customers")  
  11.     }  
  12.     // Create Object Store  
  13.     // This method was not called from a VERSION_CHANGE transaction callback.  
  14.     var objectStore = db.createObjectStore("customers", {  
  15.       // primary key  
  16.       keyPath : "ssn",  
  17.       // auto increment  
  18.       autoIncrement : true 
  19.     });  
  20.  
  21.     objectStore.createIndex("name", "name", {  
  22.       unique : false 
  23.     });  
  24.  
  25.     objectStore.createIndex("email", "email", {  
  26.       unique : false 
  27.     });  
  28.     console.log("create object store success!");  
  29.   }  

三、数据库的CRUD操作

IndexedDB操作CRUD还是比较容易的,下面分别给出样例代码

1.新增

  1. function saveObject() {  
  2.   if (!db) {  
  3.     alert("Database is not open!");  
  4.     return;  
  5.   }  
  6.   var name = document.getElementById("name").value;  
  7.   var email = document.getElementById("email").value;  
  8.   if ("" == name) {  
  9.     alert("name is null!");  
  10.     return;  
  11.   }  
  12.   //Open a transaction with a scope of data stores and a read-write mode.  
  13.   var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);  
  14.  
  15.   var store = trans.objectStore('customers');  
  16.   var customer = {};  
  17.   customer["name"] = name;  
  18.   customer["email"] = email;  
  19.   var req = store.add(customer);  
  20.   req.onsuccess = function(event) {  
  21.     console.log("save object success!(name:" + name + ",email:" + email + ")");  
  22.   };  
  23.   req.onerror = function(enent) {  
  24.     console.log("save object error:" + req.errorCode);  
  25.   };  

2.修改

  1. //Update Object  
  2. function updateObject() {  
  3.   if (!db) {  
  4.     alert("Database is not open!");  
  5.     return;  
  6.   }  
  7.   var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);  
  8.  
  9.   var store = trans.objectStore('customers');  
  10.   var customer = {};  
  11.   customer["ssn"] = parseInt(document.getElementById("key").value);  
  12.   customer["name"] = document.getElementById("u_name").value;  
  13.   customer["email"] = document.getElementById("u_email").value;  
  14.   result = store.put(customer);  
  15.   result.onerror = function(event) {  
  16.     console.log("update object error:"+result.errorCode);  
  17.   };  
  18.   result.onsuccess = function(event) {  
  19.     console.log("update object success:ssn:"+customer["ssn"]+",name:"+customer["name"]+",email:"+customer["email"] );  
  20.   };  

3.删除

  1. //Delete Object()  
  2. function deleteObject(index,obj) {  
  3.   var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);  
  4.   var store = trans.objectStore('customers');  
  5.   result = store.delete(index);  
  6.   result.onerror = function(event) {  
  7.     console.log("delete Objcet error:"+result.errorCode);  
  8.   }  
  9.   result.onsuccess = function(event) {  
  10.     console.log("delete Object success!");  
  11.     obj.disabled = true;  
  12.   }  
  13. }  

4.查找

  1. //List Objects  
  2. function listObjects() {  
  3.   if (!db) {  
  4.     alert("Database is not open!");  
  5.     return;  
  6.   }  
  7.   var trans = db.transaction(['customers'], IDBTransaction.READ_ONLY);  
  8.   var store = trans.objectStore('customers');  
  9.   var curreq = store.openCursor(IDBKeyRange.bound(1, 4), IDBCursor.PREV);  
  10.   // The "onsuccess" event fires when the cursor is created and  
  11.   // every time the cursor iterates over data.  
  12.   // The following block of code runs multiple times,  
  13.   // until the cursor runs out of data to iterate over.  
  14.   // At that point, the result's request becomes null.  
  15.   var view = document.getElementById("objcetsView");  
  16.   view.innerHTML = "";  
  17.   curreq.onsuccess = function(e) {  
  18.     var cursor = curreq.result;  
  19.     // If the cursor is pointing at something, ask for the data.  
  20.     if (cursor) {  
  21.       var getreq = store.get(cursor.key);  
  22.       // After the data has been retrieved, show it.  
  23.       getreq.onsuccess = function(e) {  
  24.         console.log('key:', cursor.key, 'value:', getreq.result);  
  25.         var value = getreq.result;  
  26.         var objLi=document.createElement("li");  
  27.         objLi.innerHTML = "key:"+cursor.key+",name:"+ value["name"]+",email:"+value["email"]+"<input type='button' value='delete' onclick='deleteObject("+cursor.key+",this)'/>";  
  28.         var updateString = "<input type='button' value='update' onclick='getUpdateObject("+cursor.key + ",\""+value["name"]+"\",\""+value["email"]+"\");'/>";  
  29.         objLi.innerHTML += updateString;  
  30.         view.appendChild(objLi);  
  31.  
  32.         // OK, now move the cursor to the next item.  
  33.         cursor.continue();  
  34.       };  
  35.     }  
  36.   };  

源码下载:http://chyblog-chyblog.stor.sinaapp.com/wp-content/uploads/2012/09/dbtest.zip

责任编辑:Yeva 来源: chyblog.com
相关推荐

2012-02-23 15:36:51

IndexedDB

2013-01-14 12:19:48

Firefox OSFirefox OS

2019-12-10 09:46:12

Elementary PantheonLinux

2013-01-14 13:21:09

Firefox os

2013-06-24 09:23:25

Firefox OS火狐手机Android

2013-01-18 10:59:44

IBMdW

2014-01-09 14:07:46

Firefox OS操作系统

2012-09-04 13:35:24

Firefox OS

2012-09-29 10:24:14

Firefox OS

2012-09-12 09:08:54

Firefox OS

2013-09-02 11:18:06

Firefox OSMarketplace

2013-01-14 13:14:11

Firefox OS

2013-01-14 12:40:56

Firefox OS

2013-01-14 12:25:49

Firefox OS

2014-06-16 10:20:46

Firefox OSWeb Apps

2015-11-12 13:47:53

Firefox OSAPPFirefox

2013-01-08 14:58:48

Firefox OS

2009-03-23 09:57:19

2013-02-25 09:15:30

MWC 2013Firefox OS

2013-02-21 13:18:32

点赞
收藏

51CTO技术栈公众号