// 定义变量,用来接收open的实例对象
let db: any;
// 打开数据库
const request = indexedDB.open("testDataBase", 3);
request.onsuccess = (event: any) => {
console.log("打开成功")
db = event.target?.result;
}
request.onerror = (e) => {
console.log("打开失败")
}
// 该回调只有在数据库新建和升级时才会触发,一般用来新建表和设置表规则
request.onupgradeneeded = (e: any) => {
const result = e.target.result;
let objectStore;
// 判断是否存在mystore表
if (!result.objectStoreNames.contains("mystore")) {
// 没有存在即创建
objectStore = result.createObjectStore("mystore", { keyPath: "id", autoIncrement: true });
// 创建索引 sy_a为索引名、a为索引对应的表字段、非必填
objectStore.createIndex("sy_a", "a", { unique: false })
} else {
// 获取表
objectStore = e.target.transaction.objectStore("mystore");
// 判断表上是否存在sy_a索引,是防止后期发现索引不够的时候需要新增索引,所以要做一下判断
if (!objectStore.indexNames.contains("sy_a")) {
objectStore.createIndex("sy_a", "a", { unique: false });
}
}
}
// 这个只是个例子,现实中是需要等待open成功以后才可以调用,可以进行封装,这儿只是简单的用来学习
// 所有的操作都有onsuccess和onerror
setTimeout(() => {
// 创建事务
const transaction = db!.transaction(['mystore'], 'readwrite');
// 访问对象仓库
const store = transaction.objectStore('mystore');
// 添加 可以指定key 有autoIncrement时可以不指定
const addStore = store.add({
b: 7
})
// 删除
const deleteStore = store.delete(1);
// 更新
const updateStore = store.put({
id: 2,
a: 6,
});
// 获取全部
const getStore = store.getAll();
// 通过key获取
const getKeyStore = store.get(1);
getKeyStore.onsuccess = (e: any) => {
console.log(e)
}
// 通过索引查询 查找a为6的数据
const v = store.index("sy_a").getAll(6);
v.onsuccess = (e: any) => {
console.log("1111")
console.log(e)
}
// 通过游标获取数据
const list: any = [];
const cursorStore = store.openCursor();
cursorStore.onsuccess = (e: any) => {
const cursor = e.target.result;
if (cursor) {
//一条一条push
list.push(e.target.result.value);
cursor.continue()
} else {
// 最终数据
console.log(list)
}
}
// 通过游标和索引进行获取
const vItem = store.index("sy_a").openCursor(IDBKeyRange.only(6));
vItem.onsuccess = (e: any) => {
console.log(e)
}
}, 1000);
09-30
1537

10-30
3032

12-09
1171

08-07
318

04-04
2449
