js操作indexedDB增删改查示例
Posted 叶家伟的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js操作indexedDB增删改查示例相关的知识,希望对你有一定的参考价值。
js操作indexedDB增删改查示例
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‘);
}
以上是关于js操作indexedDB增删改查示例的主要内容,如果未能解决你的问题,请参考以下文章
Node.js学习5~nodejs操作mysql数据库,实现增删改查