IndexedDB的基础使用

前言

近日,接触到了IndexedDB,看了下网友的答案,我不大满意,所以在此总结下基本使用。

代码

1 <html>
2     <head>
3         <meta charset="utf-8"></meta>
4         <title>IndexedDb测试</title>
5         <script src="./index.js"></script>
6     </head>
7     <body>
8     </body>
9 </html>

index.js如下:

  1 const DATABASE_NAME = "test_db";
  2 const VERSION = 1;
  3 const TABLE = "test_table";
  4 
  5 /**
  6  * 在 [db]--[tableName]中新增一条记录[data]
  7  */
  8 function addRecord(db, tableName, data) {
  9     return new Promise(function(resolve, reject) {
 10         let request = db.transaction(tableName, "readwrite")
 11         .objectStore(tableName)
 12         .add(data);
 13         request.onsuccess = function () {
 14             resolve({
 15                 code: 10000
 16             });
 17         }
 18         request.onerror = function (e) {
 19             reject({
 20                 code: 0,
 21                 msg: e.target.error
 22             })
 23         }
 24     })
 25 }
 26 
 27 /**
 28  * 获取 [db]--[tableName]下,主键为 [key] 的某条记录
 29  */
 30 function getRecord(db, tableName, key) {
 31     return new Promise(function(resolve, reject) {
 32         let request = db.transaction(tableName)
 33         .objectStore(tableName)
 34         .get(key);
 35         request.onsuccess = function (e) {
 36             resolve({
 37                 code: 10000,
 38                 data: e.target.result
 39             });
 40         }
 41         request.onerror = function (e) {
 42             reject({
 43                 code: 0,
 44                 msg: e.target.error
 45             })
 46         }
 47     })
 48 }
 49 
 50 /**
 51  * 根据索引所在位置 [_index],获取 [db]--[tableName]下,索引值为 [identify]的某条记录
 52  */
 53 function getRecordWithIndex(db, tableName, _index, identify) {
 54     return new Promise(function(resolve, reject) {
 55         let request = db.transaction(tableName, "readwrite")
 56         .objectStore(tableName)
 57         .index(_index)
 58         .get(identify);
 59         request.onsuccess = function (e) {
 60             resolve({
 61                 code: 10000,
 62                 data: e.target.result
 63             });
 64         }
 65         request.onerror = function (e) {
 66             reject({
 67                 code: 0,
 68                 msg: e.target.error
 69             })
 70         }
 71     })
 72 }
 73 
 74 /**
 75  * 读取 [db]--[tableName] 下的所有记录
 76  */
 77 function readAllRecord(db, tableName) {
 78     return new Promise(function(resolve, reject) {
 79         let objectStore = db.transaction(tableName).objectStore(tableName);
 80         let records = [];
 81         objectStore.openCursor().onsuccess = function(e) {
 82             let cursor = e.target.result;
 83             if (cursor) {
 84                 records.push(cursor.value);
 85                 cursor.continue();
 86             } else {
 87                 resolve({
 88                     code: 10000,
 89                     data: records
 90                 })
 91             }
 92         }
 93         objectStore.openCursor().onerror = function(e) {
 94             reject({
 95                 code: 0,
 96                 msg: e.target.error
 97             })
 98         }
 99     })
100 }
101 
102 /**
103  * 将 [db]--[tableName]中,主键为 [key]的数据为,更新为 [data]
104  */
105 function updateRecord(db, tableName, data, key) {
106     return new Promise(function(resolve, reject) {
107         let request = db.transaction(tableName, "readwrite")
108         .objectStore(tableName)
109         .put(data, key);
110         request.onsuccess = function() {
111             resolve({
112                 code: 10000
113             })
114         }
115         request.onerror = function (e) {
116             reject({
117                 code: 0,
118                 msg: e.target.error
119             })
120         }
121     })
122 }
123 
124 /**
125  * 在 [db]--[tableName]下,删除主键为[key]的记录
126  */
127 function deleteRecord(db, tableName, key) {
128     return new Promise(function(resolve, reject) {
129         let request = db.transaction(tableName, "readwrite")
130         .objectStore(tableName)
131         .delete(key);
132         request.onsuccess = function () {
133             resolve({
134                 code: 10000
135             });
136         }
137         request.onerror = function (e) {
138             reject({
139                 code: 0,
140                 msg: e.target.error
141             })
142         }
143     })
144 }
145 
146 /**
147  * 获取数据库对象
148  */
149 function getDB(dbName, version) {
150     return new Promise(function(resolve, reject) {
151         let request = window.indexedDB.open(dbName, version);
152         request.onsuccess = function(e) {
153             let db = e.target.result;
154             resolve(db);
155         }
156         request.onupgradeneeded = function(e) {
157             // 初始化数据库
158             let db = e.target.result;
159             if (!db.objectStoreNames.contains(TABLE)) {
160                 var objectStore = db.createObjectStore(TABLE, {autoIncrement: true});
161                 // 创建索引
162                 objectStore.createIndex("name", "name", {unique: true});
163                 objectStore.createIndex("email", "email", {unique: true});
164             };
165         }
166     })
167 }
168 
169 getDB(DATABASE_NAME, VERSION).then(db => {
170     let data = {
171         id: 1, 
172         name: "张三",
173         age: 18, 
174         email: "test@168.com"
175     }
176 
177     addRecord(db, TABLE, data).then(res => {
178         console.log(res);
179     }, err => {
180         console.log(err);
181     })
182 
183     // getRecord(db, TABLE, 1).then(res => {
184     //     console.log(res);
185     // }, err => {
186     //     console.log(err);
187     // })
188 
189     // getRecordWithIndex(db, TABLE, "email", "test@168.com").then(res => {
190     //     console.log(res);
191     // }, err => {
192     //     console.log(err);
193     // })
194 
195     // deleteRecord(db, TABLE, 1).then(res => {
196     //     console.log(res);
197     // }, err => {
198     //     console.log(err);
199     // })
200 
201     // readAllRecord(db, TABLE).then(res => {
202     //     console.log(res);
203     // }, err => {
204     //     console.log(err);
205     // })
206 
207     // updateRecord(db, TABLE, {id: 1, name: "小张三", age: 18, email: "new@168.com"}, 1).then(res => {
208     //     console.log(res);
209     // }, err => {
210     //     console.log(err);
211     // })
212 })

最后

文档在此:

https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API

推荐看看阮一峰的这篇文章:

http://www.ruanyifeng.com/blog/2018/07/indexeddb.html

posted @ 2020-10-14 23:49  明说  阅读(1036)  评论(0编辑  收藏  举报