写在前面
9月初的时候做了一个Todos,当时在想如果不做用户管理但又想让每个客户端都只显示自己的代办事项该怎么做。就想到要用indexedDB来处理一下,但是一直在实习准备秋招,今天有时间就来看看这个浏览器的数据库IndexedDB。
正篇开始
-
连接数据库 开头第一步,和操作其他数据库一样,先连接
const request = indexedDB.open('数据库名称', 数据库版本)连接时,会触发三种事件error(失败)、success(成功)、upgradeneeded(升级)
request.onerror = function(event) { // 连接失败事触发事件 } request.onsuccess = function(event) { // 连接成功触发事件 } request.onupgradeneeded = function(event) { // 数据库更新时触发事件,如果没有数据库或者更新数据库版本时,会先触发upgradeneeded事件,再触发success事件 // 数据库实例 db = event.target.result; if (!db.objectStoreNames.contains('person')) { // 新建表, 新建一个表名为person,主键为id的表(只能在更新时使用createObjectStore方法创建对象) let objectStore = db.createObjectStore('person', { keyPath: 'id' }); // 新建索引,createIndex方法分别有三个参数,分别为索引名称、索引所在的属性、配置对象(表明该属性的值是否可以重复) objectStore.createIndex('name', 'name', { unique: false }); objectStore.createIndex('email', 'email', { unique: true }); } }连接成功,就可以对数据库进行操作了
- 增
const request = db // 新建事务,参数:访问的表,以及访问权限 .transaction(['person'], 'readwrite') // 得到表实例 .objectStore('preson') // 添加数据 .add({id:1, name: '张三', age: 30, email: 'zhangsan@text.com'}) // 同时也拥有成功和失败的回调函数 request.onsuccess = function(event){ console.log('成功') } request.onerror = function(event){ console.log('失败') }- 删
const request = db .transaction('[person]', readwrite) .objectStore('person') // 删除主键为2的数据 .delete(1); // 同时也拥有成功和失败的回调函数3.改
const request = db .transaction('[person]', 'readwrite') .objectStore('person') // 更新数据,根据主键更新数据,如果没有改主键会插入一条新的数据 .put({ id: 1, name: '王五', age: 50, email: 'wangwu@example.com' })4.查
const request1 = db .transaction('[person]', 'readwrite') .objectStore('person') // 根据主键查询数据 .get(1); const request2 = db .transaction('[person]', 'readwrite') .objectStore('person') // 查询所有数据 .openCursor(); const request3 = db .transaction('[person]', 'readwrite') .objectStore('person') // 设置查询的索引值 .index('name') .get('王五'); // 所有查询到的数据都在成功回调函数中 request.onsuccess = function(event) { // 查询到的数据 let result = event.target.result }
结束
IndexedDB可能在日常开发中用处较少,但是用在本地做一些缓存数据,或者其他与数据相关联的内容,还是很不错的。