html5浏览器数据库indexedDB基本使用(增,删,查,改)
ChrisXie Lv5

前端项目开发会接触到需要前端或者说浏览器来存储一些数据减少从服务器读取数据,从Cookie(4KB左右)到LocalStorage(2.5MB 到 10MB 之间)都是会经常使用到的方式,但是存储数据量大些的时候这两个都不具备
而IndexedDB(不少于250MB)很好的能决绝这个问题而且操作相对简单(可以存储对象类型)还有很多优点可以参照阮一峰的网络日志有详细讲解。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>IndexedDb基本使用</title>
</head>
<script type="text/javascript" src="../js/jQuery.main.js"></script>
<body>
<button id = "addBtn">添加</button>
<button id = "readBtn">读取</button>
<button id = "upBtn">更新</button>
<button id= "shancBtn">删除数据库</button>
<button id = "readAll">获取所有数据</button>
</body>
</html>
<script type="text/javascript">
/**
* 说明:由于存储的数据格式问题;这里的修改没有直接修改的方式去修改,通过先查询后再通过判断是否有值后进行put()修改,如果没有值通过add(),为什么没有通过put()自动添加因为存储数据格式的问题
* 没有办法通过id和索引去判断是否重复,所以直接通过add添加,除了删除所有数据是通过对indexedDb进行操作,对单个数据的删除都是先通过JavaScript通过数据删除后再进行put更新数据。
*/
//判断是否支持
var recordDB = {
version: 1, // important: only use whole numbers!
// name:$Config.userInfoData.id,
name:"testDb",
db:null,
isSupport: function () {// support indexeddb or not
if (!window.indexedDB){
return false;
}
return true;
},
}

//调用数据库
if(recordDB.isSupport){
openDB(recordDB.name,recordDB.version,"recordsss");
// setTimeout(function(){
// addData(recordDB.db,'recordsss');
// },500);

}else{
alert("由于不支持web存储,暂不支持浏览记录查询");
}

var recordsss = {
"chat6028": [{
id: "32783370141616730",
operatorId: 2,
roomId: null,
type: "1",
msg: '<img class="lg-face" src="img / emotion / face02 / 0. gif >'
},
{
id: "32783370734305120",
operatorId: 2,
roomId: null,
type: "1",
msg: "<p>11111<br></p>"
}
],
"chat6027": [{
id: "12333",
operatorId: 2,
roomId: null,
type: "1",
msg: '<img class="lg-face" src="img / emotion / face02 / 0. gif >'
},
{
id: "22222",
operatorId: 2,
roomId: null,
type: "1",
msg: "<p>11111<br></p>"
},
{
id: "22222",
operatorId: 2,
roomId: null,
type: "1",
msg: "<p>11111<br></p>"
}
],
"chat6026": [{
id: "12333",
operatorId: 2,
roomId: null,
type: "1",
msg: '<img class="lg-face" src="img / emotion / face02 / 0. gif >'
},
{
id: "22222",
operatorId: 2,
roomId: null,
type: "1",
msg: "<p>11111<br></p>"
}
]
}

//打开数据库(初始化数据库)
function openDB(name,version,storeName){
//表示数据库的名字。如果指定的数据库不存在,就会新建数据库。第二个参数是整数,表示数据库的版本。如果省略,打开已有数据库时,默认为当前版本;新建数据库时,默认为1。
var request = window.indexedDB.open(name, version);
request.onerror = function (event) {
console.log("IndexedBD OPen Error!");
console.log(event);
}
request.onsuccess = function (event) {
console.log(event)
recordDB.db = event.target.result;//可以拿到数据库对象
}
//如果指定的版本号,大于数据库的实际版本号,就会发生数据库升级事件upgradeneeded
request.onupgradeneeded = function (event) {
console.log("当前版本号:"+(version || 1));
var db = event.target.result;
console.log(event)
console.log(db);
console.log(!db.objectStoreNames.contains(storeName));
if(!db.objectStoreNames.contains(storeName)){//判断这个表是否存在如果不存在自动新建一个表
var objectStore = db.createObjectStore(storeName,{keyPath: 'id',autoIncrement:true});//autoIncrement自增
objectStore.createIndex("keys","mkey",{ unique: false });//建立索引为keys
}
console.log('DB version changed to '+version);
}
}

//关闭数据库
function closeDB(db){
recordDB.db.close();
}

function deletaData(storeName,name){
var objectStore = transaction.objectStore(storeName);
var request = objectStore.delete(name);
request.onsuccess = function (event) {
console.log("删除成功!")
}
}

//简单的批量添加数据
function addData(db,storeName){
console.log("添加数据");
console.log(db);
console.log(storeName)
var transaction=db.transaction(storeName,'readwrite');
var store=transaction.objectStore(storeName);
for(var mkey in recordsss){
var obj ={};
obj["mkey"] = mkey;
obj["read"] = recordsss[mkey];
store.add(obj);
}
}

//更新数据
function updateData(db,storeName,upData,key){
console.log("更新数据");
console.log(db);
console.log(storeName)
var transaction = db.transaction(storeName,'readwrite');
var objectStore = transaction.objectStore(storeName);
var indexVal = objectStore.index("keys");//索引keys
var request = indexVal.get(key);
request.onerror = function(event) {
console.log('查询事务失败');
};
request.onsuccess = function(e) {
data = e.target.result;
console.log(data);
if(data != undefined && data != undefined && data != ""){
data.read = upData;
// 把更新过的对象放回数据库
var requestUpdate = objectStore.put(data);
requestUpdate.onerror = function(event) {
// 错误处理
console.log("updateData更新失败");
};
requestUpdate.onsuccess = function(event) {
console.log("通过更新更新成功");
};
}else{
var store=transaction.objectStore(storeName);
var obj ={};
obj["mkey"] = key;
obj["read"] = upData;
var requestAdd = store.add(obj);
requestAdd.onerror = function(event){
console.log("updateData更新失败");
}
requestAdd.onsuccess = function(event){
console.log("通过添加更新成功");
}
}
}
}


//根据索引查询数据
function readDB(db,storeName,index,val){
var transaction = db.transaction(storeName);
var store = transaction.objectStore(storeName);
var indexVal = store.index(index);//索引keys
var request = indexVal.get(val);
request.onerror = function(event) {
console.log('查询事务失败');
};
request.onsuccess = function(e) {
data = e.target.result;
console.log(data);
}
}

//大量数据需要添加时
function massUpdate(db,storeName,data, key) {
var transaction = db.transaction([storeName], "readwrite"),store = transaction.objectStore(storeName),ii = 0;
dataValue.push(data);
dataKey.push(key);

if (dataValue.length == 3000) {
insertNext();
}

function insertNext() {
if(ii < dataValue.length){
store.add(dataValue[ii], dataKey[ii]).onsuccess = insertNext;
++ii;
}else{
console.log(dataValue.length);
}
}
};

//获取所有信数据
function readAll(db,storeName){
var objectStore = db.transaction(storeName).objectStore(storeName);
objectStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log(cursor.value);
cursor.continue();
} else {
console.log('没有更多数据了!');
}
};
}

$("#addBtn").on("click",function(){
addData(recordDB.db,'recordsss');
});
$("#readBtn").on("click",function(){
var readData = readDB(recordDB.db,'recordsss',"keys","chat6026")
console.log(readData);
});
$("#upBtn").on("click",function(){
updateData(recordDB.db,'recordsss',recordsss["chat6026"],"chat6026");
});
$("#readAll").on("click",function(){
readAll(recordDB.db,'recordsss');
});
</script>
 评论