Electron使用Dexie操作IndexDB
Dexie.js 基本的使用
github地址
Dexie.js官网
在Vue中的使用示例
API简单使用
安装
npm install dexie
自定义数据库模块 db.ts
// db.ts
import Dexie, { Table } from 'dexie';
export interface Friend {
id?: number;
name: string;
age: number;
}
export class MySubClassedDexie extends Dexie {
// 'friends' is added by dexie when declaring the stores()
// We just tell the typing system this is the case
friends!: Table<Friend>;
constructor() {
super('myDatabase');
this.version(1).stores({
friends: '++id, name, age' // Primary key and indexed props
});
}
}
export const db = new MySubClassedDexie();
db.open();
db.on('populate',()=>{
db.friends.add({name: "Josephine", age: 21});
})
objectstore定义
语法 | 说明 |
---|---|
++ | 用于定义自增主键,字段 内容不可重复 |
& | 定义唯一索引 |
* | 定义多条目索引 |
A+B | 定义联合索引 |
必要数据初始化
db.on(‘populate’,fn) 在数据库建库时只执行一次,数据库已存在不会执行,比较适用于初始化数据库的基本数据。
插入数据
// 插入一条数据
db.friends.add({name: "Josephine", age: 21});
// 批量插入
await db.friends.bulkAdd([
{name: "Foo", age: 31},
{name: "Bar", age: 32}
]);
更新数据
// 更新一条数据,有id为4的数据对其进行更新,没有则插入
await db.friends.put({id: 4, name: "Foo", age: 33});
// 批量更新或插入
await db.friends.bulkPut([
{id: 4, name: "Foo2", age: 34},
{id: 5, name: "Bar2", age: 44}
]);
// 更新id为4的数据的名字
await db.friends.update(4, {name: "Bar"});
// 范围批量更新
await db.customers
.where("age")
.inAnyRange([ [0, 18], [65, Infinity] ])
.modify({discount: 0.5});
删除数据
// 根据id删除
await db.friends.delete(4);
// 批量删除
await db.friends.bulkDelete([1,2,4]);
const oneWeekAgo = new Date(Date.now() - 60*60*1000*24*7);
// 范围批量删除
await db.logEntries
.where('timestamp').below(oneWeekAgo)
.delete();
查询
// 通过id查询
const friend = await db.friends.get(4)
// 条件查询
const someFriends = await db.friends
.where("name")
.equals("Foo")
.toArray()
// 返回唯一结果
const firend = await db.friends
.where({
name: "Foo",
age: 33
}).first()