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 connectDatabase() {
var dbName = "indexedDBTest";
var dbVersion = 20170633
var idb;
var dbConnect = indexedDB.open(dbName, dbVersion);
//连接成功
dbConnect.onsuccess = function(e) {
idb = e.target.result;
console.log(e);
console.log("连接成功");
//开启事物
var tx = idb.transaction(["newUsers"], "readwrite");
var store = tx.objectStore("newUsers");
var value = {
userId: 1,
userName: "李四",
address: "广东省"
};
var req = store.put(value);
req.onsuccess = function(e) {
console.log("保存成功");
};
req.onerror = function(e) {
console.log("保存失败");
}
};
dbConnect.onerror = function() {
console.log("连接失败");
};
//数据库更新
dbConnect.onupgradeneeded = function(e) {
idb = e.target.result;
var tx = e.target.transaction;
var oldVersion = e.oldVersion;
var newVersion = e.newVersion;
console.log("数据库已经更新");
//添加数据
var name = "newUsers";
var optionalParameters = {
keyPath: "userId", //表示主键
autoIncrement: true //主键是否自动增长
};
//createObjectStore(仓库名称,对象)
var store = idb.createObjectStore(name, optionalParameters);
//创建唯一索引
var name = "userNameIndex";
var keyPath = "userName";
var optionalParameters = {
unique: false,
multiEntry: false
};
//创建唯一索引
var idx = store.createIndex(name, keyPath, optionalParameters);
};
}
关于indexedDB的基本使用
最新推荐文章于 2024-06-18 08:26:10 发布