const indexDB =
window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB;
class IndexDBCache {
// 构造函数
constructor() {
this._db = null; //数据库
this._transaction = null; //事务
this._request = null;
this._dbName = "we_chat_data"; //数据库名
this._cacheTableName = "user_list"; //表名
this._dbversion = 1; //数据库版本
}
// 打开数据库
openDB(name) {
this._dbName = name;
return new Promise((resolve, reject) => {
this._request = indexDB.open(this._dbName, this._dbversion); // 打开数据库
// 数据库初次创建或更新时会触发
this._request.onupgradeneeded = (event) => {
let db = this._request.result;
if (!db.objectStoreNames.contains(this._cacheTableName)) {
db.createObjectStore(this._cacheTableName, {
// 设置主键:不管是添加数据还是查询数据或者修改数据,都需要指定主键,即传递的参数必须包含key:'xxxx'
keyPath: "key", // 设置主键
});
}
// resolve(event);
};
// 数据库初始化成功
this._request.onsuccess = (event) => {
this._db = this._request.result;
resolve(event);
};
// 数据库初始化失败
this._request.onerror = (event) => {
console.log("数据库初始化失败");
reject(event);
};
});
}
// 关闭数据库
closeDB() {
this._db.close();
// console.log("数据库关闭");
}
/**
* @description : 新增数据
* @param {Object} params 添加到数据库中的
h5前端 indexDB的增删改查
于 2024-04-29 17:32:19 首次发布