html5 indexDB的使用
angular.module('indexdb', [])
.factory('indexDbJs', [function() {
const CurDBVersion = 10000;
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor || window.msIDBCursor;
var db = {
dbName: 'macImDb',
obj: {},
dbInstance: {},
errorHandler: function(error) {
// console.log('error: ' + error.target.error.message);
},
// 打开数据库,没有则自动创建
open: function(func, fail) {
// var version = db.getdbVeision();
if(db.dbName.indexOf('_')<0) {
console.error(db.dbName);
debugger;
}
var dbContent = window.indexedDB.open(db.dbName);
// dbContent.onupgradeneeded = db.upgrade;
// dbContent.onerror = db.errorHandler;
dbContent.onsuccess = function(e) {
// console.log('打开成功');
var _db = e.target.result;
db.dbInstance = dbContent.result;
db.dbInstance.onerror = function() {
};
func();
_db.close();
};
dbContent.onerror = function(e) {
var _db = e.target.result;
// console.log('打开不成功');
_db.close();
};
dbContent.onupgradeneeded = function(e) {
// console.log('更新');
var _db = e.target.result;
_db.close();
};
dbContent.onblocked = (e)=>{
console.log("onblocked");
};
},
// 关闭数据库
closeDB: function(db) {
db.close();
},
// 创建数据表
createStore: function(storeInfo, indexInfo, callback) {
var count = 0;
db.obj.stname = storeInfo.stname;
db.obj.indexInfo = indexInfo;
//创建数据库
//var version = db.getdbVeision() + 1;
// console.log(version);
// var req = window.indexedDB.open(db.dbName);
// req.onsuccess = function(e) {
// var version = e.target.result.version;
var dbContent = window.indexedDB.open(db.dbName, CurDBVersion);
// 判断数据库版本号是否更新``
// dbContent.onupgradeneeded = db.upgrade;
dbContent.onupgradeneeded = function(e) {
// console.log('更新了');
var _db = e.target.result,
names = _db.objectStoreNames;
// 此处可以创建多个表
// var name = db.obj.stname;
var name = storeInfo.stname;
if (!names.contains(name)) {
// console.log('chuagnjian');
var store = _db.createObjectStore(
db.obj.stname, {
keyPath: 'id',
autoIncrement: true
});
// 如果创建数据表时传过来的索引信息不为空则创建索引
if (db.obj.indexInfo && db.obj.indexInfo.length !== 0) {
for (var i = 0; i < db.obj.indexInfo.length; i++) {
var req = store.createIndex(db.obj.indexInfo[i].indexName, db.obj.indexInfo[i].index, { unique: false });
req.onsuccess = function() {
count++;
if (count >= indexInfo.length) {
callback(true);
_db.close();
}
};
}
} else {
callback(true);
_db.close();
}
} else {
callback(true);
_db.close();
}
},
// 创建数据库成功事件
dbContent.onsuccess = function(e) {
var _db = e.target.result;
// console.log('创建成功');
db.dbInstance = dbContent.result;
callback(true);
_db.close();
},
// 创建数据库成功事件
dbContent.onerror = function() {
// var _db = e.target.result;
// console.log('创建失败');
// callback(false);
// _db.close();
// console.log(333);
};
// }
},
/**
* 设置数据库名称
* @param dbname 数据库名称
*/
setDbName: function(dbname){
db.dbName = dbname;
},
/**
* 创建数据库和表
* @param storeInfo 表
* @param indexInfo 索引
* @param callback 回调
* @constructor
*/
CreateStores: function(storeInfo, indexInfo, callback) {
// db.obj.stname = storeInfo.stname;
db.obj.indexInfo = indexInfo;
var count = 0;
//创建数据库
//var version = db.getdbVeision();
// console.log(version);
// var req = window.indexedDB.open(db.dbName);
// req.onsuccess = function(e) {
// var version = e.target.result.version;
var dbContent = window.indexedDB.open(db.dbName, CurDBVersion);
// console.log(dbContent.getVesdion)
// 判断数据库版本号是否更新``
// dbContent.onupgradeneeded = db.upgrade;
dbContent.onupgradeneeded = function(e) {
// console.log('更新了');
var _db = e.target.result,
names = _db.objectStoreNames;
// 此处可以创建多个表
// var arr = ['dtt1', 'dttt2', 'dttt3'];
for (var i = 0; i < storeInfo.length; i++) {
var name = storeInfo[i].stname;
if (!names.contains(name)) {
var store = _db.createObjectStore(
name, {
keyPath: 'id',
autoIncrement: true
});
// 如果创建数据表时传过来的索引信息不为空则创建索引
if (db.obj.indexInfo[i] && db.obj.indexInfo[i].length !== 0) {
for (var j = 0; j < db.obj.indexInfo[i].length; j++) {
store.createIndex(db.obj.indexInfo[i][j].indexName, db.obj.indexInfo[i][j].index, { unique: false });
}
count++;
}
} else {
// callback(true);
// db.closeDB('macImDb');
//检测是否有索引更新的
var store = dbContent.transaction.objectStore(name);
for (var j = 0; j < db.obj.indexInfo[i].length; j++) {
if (!store.indexNames.contains(db.obj.indexInfo[i][j].indexName))
{
store.createIndex(db.obj.indexInfo[i][j].indexName, db.obj.indexInfo[i][j].index, {unique: false});
}
}
}
}
if (count >= storeInfo.length) {
callback(true);
}
},
// 创建数据库成功事件
dbContent.onsuccess = function(e) {
db.dbInstance = dbContent.result;
callback(true);
// db.closeDB('macImDb');
// db.dbInstance.onerror = null;
// console.log(db);
},
// 创建数据库失败事件
dbContent.onerror = function() {
callback(false);
};
// }
},
// 获得数据表
getObjectStore: function(objectStoreName, mode) {
var txn, store;
mode = mode || 'readonly';
txn = db.dbInstance.transaction([objectStoreName], mode);
store = txn.objectStore(objectStoreName);
return store;
},
// 当数据库版本更新时创建数据表
upgrade: function(e) {
// console.log('更新了');
var _db = e.target.result,
names = _db.objectStoreNames;
// 此处可以创建多个表
var name = db.obj.stname;
// console.log(db.obj.stname);
// console.log(name);
if (!names.contains(name)) {
var store = _db.createObjectStore(
db.obj.stname, {
keyPath: 'id',
autoIncrement: true
});
// 如果创建数据表时传过来的索引信息不为空则创建索引
if (db.obj.indexInfo && db.obj.indexInfo.length !== 0) {
for (var i = 0; i < db.obj.indexInfo.length; i++) {
store.createIndex(db.obj.indexInfo[i].indexName, db.obj.indexInfo[i].index, { unique: false });
}
}
}
},
// 添加数据(不负责创建表)
addStore: function(objectStoreName, data, callback) {
// 如果此处是数组在此函数内部循环,而不是循环调用add函数是否会快点。
db.open(function() {
var store, req, mode = 'readwrite';
var addNum = 0;
store = db.getObjectStore(objectStoreName, mode);
for (var i = 0; i < data.length; i++) {
var req = store.add(data[i]);
req.onsuccess = function() {
addNum++;
if (addNum >= data.length) {
callback(true);
}
};
req.onerror = function() {
callback(false);
};
}
// req = store.add(data);
// req.onsuccess = function() {
// console.log('add');
// };
// req.onerror = fail;
});
},
// 添加数据(发现没有表则创建表)
add: function(type, userId, objectStoreName, indexInfo, data, callback) {
// console.log(objectStoreName);
// console.log(data);
if (type !== null) {
objectStoreName = type + userId;
}
// console.log('add');
// indexDbJs.createStore({ stname: 'dt1' }, [], function(data) {
// console.log(data);
// })
db.createStore({ stname: objectStoreName }, indexInfo, function(result) {
if (result === true) {
// console.log(true);
// 如果此处是数组在此函数内部循环,而不是循环调用add函数是否会快点。
db.open(function() {
var store, req, mode = 'readwrite';
var addNum = 0;
store = db.getObjectStore(objectStoreName, mode);
for (var i = 0; i < data.length; i++) {
var req = store.add(data[i]);
req.onsuccess = function() {
addNum++;
if (addNum >= data.length) {
callback(true);
}
};
req.onerror = function() {
callback(false);
};
}
});
}
});
},
//更新数据表
update: function(objectStoreName, data, callback) {
db.open(function() {
var store, req, mode = 'readwrite';
var updateNum = 0;
store = db.getObjectStore(objectStoreName, mode);
if (data.length == 0) {
if (callback) {
callback(true);
}
}
for (var i = 0; i < data.length; i++) {
var req = store.put(data[i]);
req.onsuccess = function() {
updateNum++;
if (updateNum >= data.length) {
if (callback) {
callback(true);
}
}
},
req.onerror = function() {
if (callback) {
callback(true);
}
};
};
});
},
// 通过id查找数据(不加游标)
selectDataById: function(objectStoreName, id, callback) {
db.open(function() {
var store = db.getObjectStore(objectStoreName),
req = store.get(id);
req.onsuccess = function(e) {
if (!e.target.result) {
return callback(null);
}
callback(e.target.result);
};
req.onerror = function() {
callback(false);
};
});
},
// 通过自己创建的索引查找数据(不加游标)
selectSingleDataByIndex: function(objectStoreName, indexName, data, callback) {
db.open(function() {
var store = db.getObjectStore(objectStoreName);
var index = store.index(indexName);
var result = [];
var count = 0
for (var i = 0; i < data.length; i++) {
// count++;
index.get(data[i]).onsuccess = function(e) {
count++;
if (e.target.result) {
result.push(e.target.result);
}
if (count >= data.length) {
callback(result);
}
}
}
});
},
// 通过自己创建的索引查找数据(增加游标)
// selectDataByIndex: function(objectStoreName, indexName, searchData, callback) {
// db.open(function() {
// var store = db.getObjectStore(objectStoreName);
// var index = store.index(indexName);
// var data = [];
// var request = index.openCursor(IDBKeyRange.only(searchData))
// request.onsuccess = function(e) {
// var cursor = e.target.result;
// if (cursor) {
// var result = cursor.value;
// data.push(result);
// // console.log(data);
// if(result&&result!==null){
// cursor.continue();
// }else{
// }
// // console.log(result);
// }else {
// callback(data);
// }
// },
// request.onerror = callback(false);
// });
// },
// 通过自己创建的索引查找数据(增加游标)
selectDataByIndex: function(objectStoreName, indexName, searchData, callback) {
console.log('查询数据,通过自己的索引');
db.open(function() {
console.log('查询数据库');
var store = db.getObjectStore(objectStoreName);
var index = store.index(indexName);
var data = [];
console.log(searchData);
var cursor = index.openCursor(IDBKeyRange.only(searchData));
cursor.onsuccess = function(e) {
if (e.target.result) {
var result = e.target.result.value;
// var result = result.value;
// console.log(result);
data.push(result);
// console.log(data);
if (result && result !== null) {
e.target.result.continue();
} else {
console.log(result);
}
// console.log(result);
} else {
callback(data);
}
},
cursor.onerror = function() {
callback(false);
};
});
},
// 根据索引删除数据
deleteDataByIndex: function(objectStoreName, indexName, searchData, callback) {
console.log('查询数据');
db.open(function() {
console.log('查询数据库');
var store = db.getObjectStore(objectStoreName, 'readwrite');
var index = store.index(indexName);
var data = [];
var cursor = index.openCursor(IDBKeyRange.only(searchData));
cursor.onsuccess = function(e) {
if (e.target.result) {
var result = e.target.result.value;
// var result = result.value;
console.log(result);
store.delete(result.id);
// console.log(data);
if (result && result !== null) {
e.target.result.continue();
} else {
}
// console.log(result);
} else {
if(callback){
callback(true);
}
}
},
cursor.onerror = function() {
callback(false);
};
});
},
deleteDataById: function(objectStoreName, id, callback) {
db.open(function() {
var
mode = 'readwrite',
store, req;
store = db.getObjectStore(objectStoreName, mode);
// console.log('要删除的id'+id);
// console.log(typeof id);
req = store.delete(id);
req.onsuccess = function(){
// console.log('删除ok');
callback(true);
};
req.onerror = function(){
callback(false);
};
});
},
// 根据id范围获取数据
selectDataByIdRange: function(objectStoreName, indexName, startId, endId, callback) {
db.open(function() {
var store = db.getObjectStore(objectStoreName);
var index = store.index(indexName);
var boundKeyRange = IDBKeyRange.bound(startId, endId, false, true);
var data = [];
// req = store.get(id);
index.openCursor(boundKeyRange).onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
// Do something with the matches.
// console.log(cursor.value);
data.push(cursor.value);
cursor.continue();
} else {
callback(data);
}
}
});
},
// 获得一个数据表的所有数据
selectAll: function(objectStoreName, callback) {
db.open(function() {
var
store = db.getObjectStore(objectStoreName),
cursor = store.openCursor(),
data = [];
cursor.onsuccess = function(e) {
var result = e.target.result;
if (result && result !== null) {
data.push(result.value);
result.continue();
// callback(data);
} else {
callback(data);
}
};
cursor.onerror = function() {
callback(false);
};
});
},
// 清空某个数据表
// deleteAllDate: function(dbName,objectStoreName) {
// var version=db.getdbVeision()
// db.open(dbName);
// },
// 删除某个数据表
// deleteStore: function(objectStoreName) {
// db.open(function() {
// // if (db.objectStoreNames.contains(objectStoreName)) {
// db.deleteObjectStore(objectStoreName);
// // }
// });
// },
deleteAllStore: function(objectStoreName, success, fail) {
},
// 删除某个数据库
deleteDB: function(dbName) {
indexedDB.deleteDatabase(dbName);
},
// 获得数据库当前版本
getdbVeision: function() {
var dbVersion = parseInt(localStorage.getItem("dbVersion")) || 1;
dbVersion++;
localStorage.setItem("dbVersion", dbVersion);
return dbVersion;
// return +new Date();
}
};
return db;
}]);
html5 indexDB的使用的更多相关文章
- HTML5项目笔记10:使用HTML5 IndexDB设计离线数据库
之前的文章(http://www.cnblogs.com/wzh2010/archive/2012/05/22/2514017.html)里面描述了HTML5 离线数据存储的Web SQL,一个基于S ...
- HTML5:离线存储(缓存机制)-IndexDB
https://www.w3.org/TR/IndexedDB/ .. <!DOCTYPE html> <html> <head> <meta charset ...
- html5中的indexDB
1.关系型数据库和非关系型数据库 一致性: 事务完成时,必须让所有的数据具有一致的状态,例如要写入100个数据,前99个成功了,结果第100个不合法,此时事务会回滚到最初状态.这样保证事务结束和开始时 ...
- HTML5 学习总结(三)——本地存储
一.HTML4客户端存储 B/S架构的应用大量的信息存储在服务器端,客户端通过请求响应的方式从服务器获得数据,这样集中存储也会给服务器带来相应的压力,有些数据可以直接存储在客户端,传统的Web技术中会 ...
- 五大主流浏览器 CSS3 和 HTML5 兼容性大比拼
各大主流浏览器对 CSS3 和 HTML5 的支持越来越完善,曾经让多少前端开发人员心碎的IE系也开始拥抱标准.就在前几天,W3C的 HTML5 社区领袖 Shelley 宣布,HTML5的开发工作已 ...
- HTML5存储之 indexedDB
IndexeDB是HTML5 重要的一部分,它是一种轻量级的NOSQL数据库.对创建具有丰富本地存储数据的数据密集型的离线HTML5 Web 应用程序很有用. IndexedDB是为了能够在客户端存储 ...
- HTML5 离线缓存管理库
一.HTML5离线缓存技术 支持离线缓存是HTML5中的一个重点,离线缓存就是让用户即使在断网的情况下依然可以正常的运行应用.传统的本地存储数据的方式有 localstorage,sessionsto ...
- HTML5和CSS3新特性一览
HTML5 1.HTML5 新元素 HTML5提供了新的元素来创建更好的页面结构: 标签 描述 <article> 定义页面独立的内容区域. <aside> 定义页面的侧边栏内 ...
- html5 之本地数据存储
HTML5 提供了两种在客户端存储数据的新方法: localStorage - 没有时间限制的数据存储 sessionStorage - 针对一个 session 的数据存储 cookie与webSt ...
随机推荐
- Android宝典入门篇-基础知识
今天跟大家分享的是我学android时的笔记.以前搞net很多年了,现在还在搞这.本着活到老学到老抽了点时间学习了下android.android网上有很多的视频教程,当时对于我这样以前不了解java ...
- OpenRISC自定义指令GCC修改
This short tutorial shows how to use the custom instructions defined by OpenRISC architecture. The O ...
- vnstat 查看服务器带宽统计命令
vnStat是一个Linux下的网络流量监控软件,它记录指定网卡每日的传输流量日志. 它并非基于网络包的过滤,而是分析文件系统- /proc, 所以vnStat无需root的权限就可使用. ,它还自带 ...
- Centos7 启动 python脚本
假设文件夹\home\sks\python3_crawl下面有个test.py 文件 打开terminal终端:转到root模式 进入cd /hom/sks/python3_crawl 执行:pyth ...
- XMPPFrameWork IOS 开发(三)登录
原始地址:XMPPFrameWork IOS 开发(三) XMPP中常用对象们: XMPPStream:xmpp基础服务类 XMPPRoster:好友列表类 XMPPRosterCoreDataSto ...
- Mac版小黑屋提示无法确认开发者身份的解决办法
Mac版小黑屋提示无法确认开发者身份的解决办法 学习了:https://jingyan.baidu.com/article/37bce2be703fa21003f3a259.html 需要按住cont ...
- linux嵌入式系统交叉开发环境
交叉开发的特点是使用交叉开发环境编译出目标机上可以运行的二进制程序. tool chain就是一整套的交叉开发工具,包括cross assembler.cross compiler. cross li ...
- POJ 2823 UESTCoj 1221 Sliding Window 单调队列 经典入门题
题意:给出一个序列,求出每连续k个数字中最大的数和最小的数. 这是道单调队列裸题,直接写就行了. 本来用deque写出来后,发现在poj上硬是超时了,在discuss上看很多人也在抱怨超时的问题,据说 ...
- quartz.net持久化和集群【转】
在实际使用quartz.net中.持久化能保证实例重启后job不丢失. 集群能均衡服务器压力和解决单点问题. quartz.net在这二块配置都比较方便,来看下. 一:持久化 quartz.net的持 ...
- Android DataBinding库(MVVM设计模式)
什么是MVVM 说到DataBinding,就有必要先提起MVVM设计模式.Model–View–ViewModel(MVVM) 是一个软件架构设计模式,相比MVVM,大家对MVC或MVP可能会更加熟 ...