标签:reac 增删改 err rem index uniq object write key
if (‘indexedDB‘ in window) {
// 如果数据库不存在则创建,如果存在但是version更大,会自动升级不会复制原来的版本
var req = indexedDB.open("TestDB", 1);
req.onupgradeneeded = function(e) {
var db = req.result;
// var store = db.createObjectStore("student", {autoIncrement: true}); 使用自增键
// 创建student表
var store = db.createObjectStore("student", {keyPath: ‘id‘});
// 设置id为主键
store.createIndex(‘student_id_unqiue‘,‘id‘, {unique: true});
}
req.onsuccess = function(event) {
var students = [
{id: 1, name: ‘小叶‘, age: ‘11‘},
{id: 2, name: ‘小王‘, age: ‘12‘},
{id: 3, name: ‘小张‘, age: ‘13‘}
];
var db = event.target.result;
// var transaction = db.transaction(‘student‘, ‘readwrite‘);
var transaction = db.transaction([‘student‘], ‘readwrite‘);
transaction.onsuccess = function(event) {
console.log(‘[Transaction] 好了!‘);
};
var studentsStore = transaction.objectStore(‘student‘);
students.forEach(function(student){
var db_op_req = studentsStore.add(student);
db_op_req.onsuccess = function() {
console.log("存好了");
}
});
studentsStore.count().onsuccess = function(event) {
console.log(‘学生个数‘, event.target.result);
};
// 获取id为1的学生
studentsStore.get(1).onsuccess = function(event) {
console.log(‘id为1的学生‘, event.target.result);
};
// 更新id为1的学生
students[0].name = ‘小小叶‘;
studentsStore.put(students[0]).onsuccess = function(event) {
console.log(‘更新id为1的学生姓名‘, event.target.result);
};
// 删除id为2的学生
studentsStore.delete(2).onsuccess = function(event) {
console.log(‘id为2的学生已经删除‘);
};
}
req.onerror = function() {
console.log("数据库出错");
}
}else{
console.log(‘你的浏览器不支持IndexedDB‘);
}
标签:reac 增删改 err rem index uniq object write key
原文地址:https://www.cnblogs.com/ye-hcj/p/10353187.html