Electron使用Dexie操作IndexDB

文章介绍了如何在Electron应用中利用Dexie.js这个轻量级的IndexedDB封装库来管理数据库。通过安装Dexie.js,自定义数据库模块,定义objectstore,以及执行初始化数据、插入、更新、删除和查询等操作,详细展示了Dexie.js在Vue环境中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值