1、引入Dexie.js
<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>
2、创建数据库
// 创建Dexie数据库MyDatabase
const db = new Dexie('MyDatabase');
// 在数据库MyDatabase创建表friends
//friends中id是自增的,name和age字段是索引,不是说表只有这两条数据
//Dexie.js是懒加载的,只有当第一条数据加入以后,indexedDB中才有表和数据
db.version(1).stores({
friends: '++id, name, age'
});
3、增加数据
db.friends.add({
name: 'Camilla',
age: 25,
street: 'East 13:th Street',
});
db.friends.add({
name: 'Paras',
age: 10,
street: 'East 15:th Street',
});
4、修改数据
db.friends.put({
id: 1,
name: 'Camilla',
age: 30,
street: 'East 30:th Street'
});
5、查询数据
// 这个是promise得用await
//查询
const oldFriends = await db.friends.get(1);
console.log(oldFriends);
6、高级查询
// 这个是promise得用await
//高级查询:查询年龄小于25的
console.log('高级查询:查询年龄小于25的↓');
const youngFriends = await db.friends.where("age").below(25).toArray();
console.log(JSON.stringify(youngFriends));
如下图是可选的方法:
7、关闭数据库
db.close();
8、例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script> </head> <script> async function openIDB() { // 创建Dexie数据库MyDatabase const db = new Dexie('MyDatabase'); db.version(1).stores({ friends: '++id, name, age' }); //增加数据 db.friends.add({ name: 'Camilla', age: 25, street: 'East 13:th Street', }); db.friends.add({ name: 'Paras', age: 10, street: 'East 15:th Street', }); //修改数据 db.friends.put({ id: 1, name: 'Camilla', age: 30, street: 'East 30:th Street' }); //查询 console.log('查询第一条数据↓'); const oldFriends = await db.friends.get(1); console.log(oldFriends); //高级查询:查询年龄小于25的 console.log('高级查询:查询年龄小于25的↓'); const youngFriends = await db.friends.where("age").below(25).toArray(); console.log(JSON.stringify(youngFriends)); } </script> <body> <button type="button" onclick="openIDB()">打开数据库</button> </body> </html>
也可以参考Dexie.js官方网站、github和b站教学视频:
https://github.com/dfahlander/Dexie.js