HTML5のIndexedDB
IndexedDB简介
IndexDB属于nosql数据库类型,支持索引,游标
操作步骤
- 连接数据库
- 触发onsuccess、onerror、onupgradeneeded事件执行业务逻辑
- 获取IDBDatabase对象、Transaction对象
- [创建ObjectStore对象以及创建索引](非必须)
- [使用游标根据索引查询数据](非必须)
分段示例
初始化数据
<script type="text/javascript">
var info = {
dbName: "GUEST",
dbVersion: 1,
storeName: "user",
optional: {
keyPath: "userid"
},
storeMode: "readwrite",
storeReadMode: "readonly",
indexNames: ["usernameIndex", "levelIndex"],
indexColumns: ["username", "level"],
indexModes: [{unique: true}, {unique: false}],
datas: [{
userid: "1204020305",
username: "Dudu",
password: "Dudu",
level: 1
}, {
userid: "1204020306",
username: "Junniang",
password: "Junniang",
level: 2
}, {
userid: "1204020307",
username: "Xiaodong",
password: "Xiaodong",
level: 3
}, {
userid: "1204020308",
username: "Liuxin",
password: "Liuxin",
level: 4
}]
};
</script>
连接数据库
<script type="text/javascript">
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
function connectionDB() {
var idb = null;
var openRequest = window.indexedDB.open(info.dbName, info.dbVersion);
openRequest.onsuccess = function() {
idb = openRequest.result;
console.log("Connection successfully.");
// addData(idb, info.storeName, info.storeMode, info.datas);
// displayData(idb, info.storeName, info.storeReadMode);
displayDataByIndex(idb, info.storeName, info.storeReadMode, info.indexNames[0]);
}
openRequest.onerror = function() {
console.log("Connection failed.");
return;
}
openRequest.onupgradeneeded = function(event) {
idb = event.target.result;
// this part will use to debug
// console.log("Event onupgradeneeded execution.");
// updateVersion(2, event);
// createStoreAndIndex(idb, info.storeName, info.optional, info.indexNames, info.indexColumns, info.indexModes);
}
}
</script>
更新版本信息
<script type="text/javascript">
function updateVersion(version, event) {
info.version = info.version < version ? version : info.version;
var oldVersion = event.oldVersion;
var newVersion = event.newVersion;
console.log("Version changed, " + oldVersion + " to " + newVersion + ".");
}
</script>
创建objectStore和index
<script type="text/javascript">
function createStoreAndIndex(idb, storeName, optional, indexNames, indexColumns, indexModes) {
if (typeof idb != "undefined") {
if (!idb.objectStoreNames.contains(storeName)) {
var userStore = idb.createObjectStore(storeName, optional);
for (var i = 0; i < indexNames.length; i++) {
userStore.createIndex(indexNames[i], indexColumns[i], indexModes[i]);
}
console.log("Create object store and index successfully.")
} else {
console.log(storeName + " objectStore is existed.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
}
</script>
添加数据并展示
<script type="text/javascript">
function addData(idb, storeName, storeMode, datas) {
if (datas.length == 0) {
console.log("Datas have no data.");
return;
}
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
for(var i = 0; i < datas.length; i++) {
var objectStoreRequest = userStore.add(datas[i]);
objectStoreRequest.onsuccess = function() {
console.log("item added to database.");
}
}
}
function displayData(idb, storeName, storeReadMode) {
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeReadMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
userStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
var userObj = cursor.value;
console.log(
userObj.userid + ", " +
userObj.username + ", " +
userObj.password + ", " + userObj.level);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
}
}
</script>
根据索引,使用游标展示数据
<script type="text/javascript">
function displayDataByIndex(idb, storeName, storeReadMode, indexName) {
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeReadMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
var usernameIndex = userStore.index(indexName);
usernameIndex.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
var userObj = cursor.value;
console.log(
userObj.userid + ", " +
userObj.username + ", " +
userObj.password + ", " + userObj.level);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
}
}
</script>
完整代码
完整Demo如下,测试过程中,将注释代码释放方可调试
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<noscript>Your browser does not support JavaScript pluin</noscript>
<script type="text/javascript">
var info = {
dbName: "GUEST",
dbVersion: 3,
storeName: "user",
optional: {
keyPath: "userid"
},
storeMode: "readwrite",
storeReadMode: "readonly",
indexNames: ["usernameIndex", "levelIndex"],
indexColumns: ["username", "level"],
indexModes: [{unique: true}, {unique: false}],
datas: [{
userid: "1204020305",
username: "Dudu",
password: "Dudu",
level: 1
}, {
userid: "1204020306",
username: "Junniang",
password: "Junniang",
level: 2
}, {
userid: "1204020307",
username: "Xiaodong",
password: "Xiaodong",
level: 3
}, {
userid: "1204020308",
username: "Liuxin",
password: "Liuxin",
level: 4
}]
};
window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
function connectionDB() {
var idb = null;
var openRequest = window.indexedDB.open(info.dbName, info.dbVersion);
openRequest.onsuccess = function() {
idb = openRequest.result;
console.log("Connection successfully.");
// addData(idb, info.storeName, info.storeMode, info.datas);
// displayData(idb, info.storeName, info.storeReadMode);
displayDataByIndex(idb, info.storeName, info.storeReadMode, info.indexNames[0]);
}
openRequest.onerror = function() {
console.log("Connection failed.");
return;
}
openRequest.onupgradeneeded = function(event) {
idb = event.target.result;
// this part will use to debug
// console.log("Event onupgradeneeded execution.");
// updateVersion(2, event);
// createStoreAndIndex(
// idb, info.storeName, info.optional, info.indexNames, info.indexColumns, info.indexModes);
}
}
function updateVersion(version, event) {
info.version = info.version < version ? version : info.version;
var oldVersion = event.oldVersion;
var newVersion = event.newVersion;
console.log("Version changed, " + oldVersion + " to " + newVersion + ".");
}
function createStoreAndIndex(idb, storeName, optional, indexNames, indexColumns, indexModes) {
if (typeof idb != "undefined") {
if (!idb.objectStoreNames.contains(storeName)) {
var userStore = idb.createObjectStore(storeName, optional);
for (var i = 0; i < indexNames.length; i++) {
userStore.createIndex(indexNames[i], indexColumns[i], indexModes[i]);
}
console.log("Create object store and index successfully.")
} else {
console.log(storeName + " objectStore is existed.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
}
function addData(idb, storeName, storeMode, datas) {
if (datas.length == 0) {
console.log("Datas have no data.");
return;
}
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
for(var i = 0; i < datas.length; i++) {
var objectStoreRequest = userStore.add(datas[i]);
objectStoreRequest.onsuccess = function() {
console.log("item added to database.");
}
}
}
function displayData(idb, storeName, storeReadMode) {
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeReadMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
userStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
var userObj = cursor.value;
console.log(
userObj.userid + ", " +
userObj.username + ", " +
userObj.password + ", " + userObj.level);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
}
}
function displayDataByIndex(idb, storeName, storeReadMode, indexName) {
var userStore = null;
var transaction = null;
if (typeof idb != "undefined") {
if (idb.objectStoreNames.contains(storeName)) {
transaction = idb.transaction([storeName], storeReadMode);
transaction.oncomplete = function() {
console.log("Transaction opened for task addition.");
}
transaction.onerror = function() {
console.log("Transaction not opened due to error. Duplicate items not allowed.");
return;
}
userStore = transaction.objectStore(storeName);
} else {
console.log(storeName + " objectStore does not exist.");
return;
}
} else {
console.log("IDBDatabase is undefined.");
return;
}
var usernameIndex = userStore.index(indexName);
usernameIndex.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
var userObj = cursor.value;
console.log(
userObj.userid + ", " +
userObj.username + ", " +
userObj.password + ", " + userObj.level);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
}
}
</script>
<style type="text/css">
#status {
width: 600px;
height: 100px;
border:#CCDD99 1px solid;
margin:0 auto;
}
#operate {
text-align: center;
margin-top: 10px;
}
</style>
</head>
<body>
<div id="status">
<span id="detail"></span>
</div>
<div id="operate">
<button type="button" onclick="connectionDB()">connection</button>
</div>
</body>
</html>