基本思想:
window.indexedDB =
window.indexedDB ||
window.webkitIndexedDB ||
window.mozIndexedDB ||
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;
function SaveData() {
var dbName = 'indexedDBTest'; // 数据库名 var
dbVersion = 20220430; // 版本号 var idb; var
dbConnect = indexedDB.open(dbName, dbVersion);
dbConnect.onsuccess = function (e) {
idb = e.target.result;
var t = idb.transaction(['users'], 'readwrite');
var s = t.objectStore('users');
console.log(store); // ->{IDBObjectStore}
var v = { userID: 1, userName: '王五', address: '北京' };
var r = s.put(v);
r.onsuccess = function (e) {
console.log('数据保存成功');
};
r.onerror = function (e) {
console.log('数据保存失败');
};
};
dbConnect.onerror = function (e) {
console.log('连接 indexedDB 数据库失败');
};
}
根据对象仓库的主键是内联主键还是外部主键,主键是否被指定为自增主键,对象仓库的 put() 的第一个参数值的指定方法也各不相同,具体指定方法如下所示:
// 主键为自增、内联主键时不需要指定主健值
store.put({
userName: '谭小胖',
address: '魏县',
}); // 主键为内联、非自增主键时需要指定主键值
store.put({ userTd: 1, userName: '谭小胖', address: '魏县' });
// 主健为外部主键时,需要另行指定主健值,此处主键值为 1
store.put({ userName: '谭小胖', address: '魏县' }, 1);
当主键为自增、内联主键时不需要指定主键值,当主键为外部主键时,可以将主键值指定为 put() 方法的第二个参数值
在 indexedDB API 中,对象仓库还有一个 add() 方法,该方法的使用方法与作用类似于对象仓库的 put() 方法区别在于当使用put() 方法保存数据时,如果指定的主键值在对象仓库中已存在,那么该主键值所在数据被更为使用 put() 方法所保存的数据,而在使用 add() 方法保存数据时,如果指定的主键值在对象仓库中已存在,引么保存失败。因此,当出于某些原因只能向对象仓库中追加数据,而不能更新原有数据时,建议使用 at0)法,而 put() 方法在其它场合使用