indexedDB是HTML5-WebStorage的重要一环,是一种轻量级NOSQL数据库。相比web sql(sqlite)更加高效,包括索引、事务处理和健壮的查询功能。indexedDB特点:
1、indexedDB常用方法:
1)获得indexedDB对象:(这一步相当于传统数据库中的创建数据库)
if (!window.indexedDB) {  
    window.indexedDB = window.mozIndexedDB || window.webkitIndexedDB;  
}  
request.onupgradeneeded = function(event) {
  alert(event.oldVersion);
  db = request.result;
  if (db.objectStoreNames.contains('books')) {  
<span style="white-space:pre">	</span>db.deleteObjectStore('books');
  }
  var store = db.createObjectStore("books", {keyPath: "isbn"});
  var titleIndex = store.createIndex("by_title", "title", {unique: true});
  var authorIndex = store.createIndex("by_author", "author");
  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456,other:"..ceshi...."});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 3456780000000000000});
};
var request = indexedDB.open("MyTestDatabase");  
request.onsuccess = function(e) {  
    var db = request.result;  
} 
注:indexedDB标准建议,在初始化的时候创建表。以后每次打开浏览器,只需要check版本号,不需要第二次创建。(只有当版本变化或者第一次时采调用onupgradeneeded方法)
2)初始化objectStore:(相当于传统数据库中的表)request.onupgradeneeded = function(event) {
  alert(event.oldVersion);
  db = request.result;
  if (db.objectStoreNames.contains('books')) {  
	db.deleteObjectStore('books');
  }
  var store = db.createObjectStore("books", {keyPath: "isbn"});
  var titleIndex = store.createIndex("by_title", "title", {unique: true});
  var authorIndex = store.createIndex("by_author", "author");
  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456,other:"..ceshi...."});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 3456780000000000000});
};注:
1.在indexedDB中,类似列数据库,所以没有列的概念,存储的是无层次限制的json对象。
2.可以通过index创建索引。
3)事务、游标
1.在indexedDB中,事务会自动提交或回滚。所以无需手动commit或者rollback。
事务分为三种
IDBTransaction.READ_ONLY              只读
IDBTransaction.READ_WRITE            可读可写
IDBTransaction.VERSION_CHANGE    版本升级
我们用的最多的是前两种。如果不设置事务级别,则默认为READ_ONLY。
2.游标,是遍历object store的唯一方法。如果在打开游标的时候不设置,默认采用IDBCursor.NEXT。在调用了cursor.continue之后,cursor会重新调用onsuccess句柄上的方法。
// 通过IDBDatabase得到IDBTransaction  
var transaction = db.transaction(["customers"]);  
  
// 通过IDBTransaction得到IDBObjectStore  
var objectStore = transaction.objectStore("customers");  
  
// 打开游标,遍历customers中所有数据  
objectStore.openCursor().onsuccess = function(event) {  
              
    var cursor = event.target.result;  
              
    if (cursor) {  
        var key = cursor.key;  
        var rowData = cursor.value;  
        alert(rowData.name);  
        cursor.continue();  
    }  
}  
// 只取得当前索引的值为Bill的数据  
IDBKeyRange.only("Bill");  
  
// 只取得当前索引的值大于Bill,并且不包括Bill的数据  
IDBKeyRange.lowerBound("Bill", true);  
  
// 只取得当前索引的值小于Bill,并且包括Bill的数据  
IDBKeyRange.upperBound("Bill", false);  
  
// 取得当前索引的值介于Bill和Jack之间,并且包括Bill,但不包括Jack的数据  
IDBKeyRange.bound("Bill", "Jack", false, true);   2)openCursor的第二个参数为游标方向。有4种var boundKeyRange = IDBKeyRange.upperBound("Jack", false);  
objectStore.index("name").openCursor(boundKeyRange, IDBCursor.PREV_NO_DUPLICATE).onsuccess = function(event) {  
        var cursor = event.target.result;  
          
        if (!cursor) {  
            return;  
        }  
          
        var rowData = cursor.value;  
          
        alert(rowData.name);  
        cursor.continue();  
    }; 2、实例:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://www.jeasyuicn.com/cron/jquery.min.js"></script>
<script type="text/javascript">
var db = null;
if (!window.indexedDB) {
    window.indexedDB = window.mozIndexedDB || window.webkitIndexedDB;  
}
  
var request = indexedDB.open("test",3);
request.onupgradeneeded = function(event) {
  alert(event.oldVersion);
  db = request.result;
  if (db.objectStoreNames.contains('books')) {  
	db.deleteObjectStore('books');
  }
  var store = db.createObjectStore("books", {keyPath: "isbn"});
  var titleIndex = store.createIndex("by_title", "title", {unique: true});
  var authorIndex = store.createIndex("by_author", "author");
  // Populate with initial data.
  store.put({title: "Quarry Memories", author: "Fred", isbn: 123456,other:"..ceshi...."});
  store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  store.put({title: "Bedrock Nights", author: "Barney", isbn: 3456780000000000000});
};
request.onsuccess = function() {
  db = request.result;
};
//通过事务、索引获取数据
function getDatas() {
	var tx = db.transaction("books", "readonly");
	var store = tx.objectStore("books");
	var index = store.index("by_title");
	var request = index.get("Bedrock Nights");
	request.onsuccess = function() {
	  var matching = request.result;
	  if (matching !== undefined) {
		// A match was found.
		$("#d1").html(matching.isbn+";"+matching.title+";"+matching.author);
	  } else {
		// No match was found.
		$("#d1").html(123);
	  }
	};
}
//通过事务、游标、索引获取数据
function getDatas1() {
	var tx = db.transaction("books", "readonly");
	var store = tx.objectStore("books");
	var index = store.index("by_author");
	var request = index.openCursor(IDBKeyRange.only("Fred"));
	var tmp  = "";
	request.onsuccess = function(event) {
	  var cursor = request.result;//也可以写成var cursor = event.target.result;  
	  if (cursor) {
		tmp+=cursor.value.isbn+";"+cursor.value.title+";"+cursor.value.author;
		cursor.continue();
	  } else {
		$("#d1").html('错误...');
	  }
	  $("#d1").html(tmp);
	};
}
function deleteDb() {
	var deleteDbRequest = indexedDB.deleteDatabase('test');
	deleteDbRequest.onsuccess = function (event) {
      alert('success...');
    };
    deleteDbRequest.onerror = function (e) {
      alert('error...');
    };
}
</script>
</head>
<body>
indexdb demo...<br/>
<button onclick="getDatas();">获取数据</button><br/>
<button onclick="getDatas1();">获取数据1</button><br/>
<button onclick="deleteDb();">删除数据库</button><br/>
<div id="d1"></div>
</body>
</html>
http://www.w3.org/TR/IndexedDB/
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/liuxiao723846/article/details/47085839