截至到现在IndexedDB,不同的厂商提供的调用方式可能会有所差异。本文针对firefox os,对IndexedDB的常用的使用进行说明。本文的示例在firefox os和firfox浏览器进行过测试。其他浏览器的使用请根据相关API文档进行修改。
IndexedDB是存储和快速检索结构型数据的客户端API,数据采用key/value的形式,value可以是结构型的数据对象,如json对象。
一、打开一个数据库
- //Open IndexedDB
- function openDB() {
- var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
- var request = indexedDB.open("B2GDBTest", 1);
- request.onsuccess = function(event) {
- console.log("database open success:" + request.result);
- db = request.result;
- };
- request.onupgradeneeded = function(event) {
- createObjectStore(event.target.result);
- };
- request.onerror = function(event) {
- console.log("database open error:" + request.errorCode);
- };
- }
首先需要获取一个IDBFactory对象,目前不同的浏览器获取的方法有所不同,可以使用下面的写法来兼容不同的浏览器(本文的DEMO只针对firefox os或者firefox浏览器)
- var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
使用IDBFactory
- 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的操作可以参考如下代码
- //Create Object Store
- function createObjectStore(db) {
- if (!db) {
- alert("Database is not open!");
- return;
- }
- if (db.version == 1) {
- if (db.objectStoreNames.contains('customers')) {
- db.deleteObjectStore("customers")
- }
- // Create Object Store
- // This method was not called from a VERSION_CHANGE transaction callback.
- var objectStore = db.createObjectStore("customers", {
- // primary key
- keyPath : "ssn",
- // auto increment
- autoIncrement : true
- });
- objectStore.createIndex("name", "name", {
- unique : false
- });
- objectStore.createIndex("email", "email", {
- unique : false
- });
- console.log("create object store success!");
- }
- }
三、数据库的CRUD操作
IndexedDB操作CRUD还是比较容易的,下面分别给出样例代码
1.新增
- function saveObject() {
- if (!db) {
- alert("Database is not open!");
- return;
- }
- var name = document.getElementById("name").value;
- var email = document.getElementById("email").value;
- if ("" == name) {
- alert("name is null!");
- return;
- }
- //Open a transaction with a scope of data stores and a read-write mode.
- var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);
- var store = trans.objectStore('customers');
- var customer = {};
- customer["name"] = name;
- customer["email"] = email;
- var req = store.add(customer);
- req.onsuccess = function(event) {
- console.log("save object success!(name:" + name + ",email:" + email + ")");
- };
- req.onerror = function(enent) {
- console.log("save object error:" + req.errorCode);
- };
- }
2.修改
- //Update Object
- function updateObject() {
- if (!db) {
- alert("Database is not open!");
- return;
- }
- var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);
- var store = trans.objectStore('customers');
- var customer = {};
- customer["ssn"] = parseInt(document.getElementById("key").value);
- customer["name"] = document.getElementById("u_name").value;
- customer["email"] = document.getElementById("u_email").value;
- result = store.put(customer);
- result.onerror = function(event) {
- console.log("update object error:"+result.errorCode);
- };
- result.onsuccess = function(event) {
- console.log("update object success:ssn:"+customer["ssn"]+",name:"+customer["name"]+",email:"+customer["email"] );
- };
- }
3.删除
- //Delete Object()
- function deleteObject(index,obj) {
- var trans = db.transaction(['customers'], IDBTransaction.READ_WRITE);
- var store = trans.objectStore('customers');
- result = store.delete(index);
- result.onerror = function(event) {
- console.log("delete Objcet error:"+result.errorCode);
- }
- result.onsuccess = function(event) {
- console.log("delete Object success!");
- obj.disabled = true;
- }
- }
4.查找
- //List Objects
- function listObjects() {
- if (!db) {
- alert("Database is not open!");
- return;
- }
- var trans = db.transaction(['customers'], IDBTransaction.READ_ONLY);
- var store = trans.objectStore('customers');
- var curreq = store.openCursor(IDBKeyRange.bound(1, 4), IDBCursor.PREV);
- // The "onsuccess" event fires when the cursor is created and
- // every time the cursor iterates over data.
- // The following block of code runs multiple times,
- // until the cursor runs out of data to iterate over.
- // At that point, the result's request becomes null.
- var view = document.getElementById("objcetsView");
- view.innerHTML = "";
- curreq.onsuccess = function(e) {
- var cursor = curreq.result;
- // If the cursor is pointing at something, ask for the data.
- if (cursor) {
- var getreq = store.get(cursor.key);
- // After the data has been retrieved, show it.
- getreq.onsuccess = function(e) {
- console.log('key:', cursor.key, 'value:', getreq.result);
- var value = getreq.result;
- var objLi=document.createElement("li");
- objLi.innerHTML = "key:"+cursor.key+",name:"+ value["name"]+",email:"+value["email"]+"<input type='button' value='delete' onclick='deleteObject("+cursor.key+",this)'/>";
- var updateString = "<input type='button' value='update' onclick='getUpdateObject("+cursor.key + ",\""+value["name"]+"\",\""+value["email"]+"\");'/>";
- objLi.innerHTML += updateString;
- view.appendChild(objLi);
- // OK, now move the cursor to the next item.
- cursor.continue();
- };
- }
- };
- }
源码下载:http://chyblog-chyblog.stor.sinaapp.com/wp-content/uploads/2012/09/dbtest.zip