首页 技术 正文
技术 2022年11月19日
0 收藏 499 点赞 2,621 浏览 1395 个字

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');
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,956
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,480
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,327
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,110
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,741
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,776