当前位置: 首页 > news >正文

Dexie.js 使用教程

Dexie.js 是一个基于 IndexedDB 的轻量级 JavaScript 库,它提供了更简单、更友好的 API 来操作浏览器中的 IndexedDB 数据库。下面是 Dexie.js 的基本使用教程。

1. 安装 Dexie.js

可以通过 npm 或直接通过 CDN 引入 Dexie.js:

npm 安装

npm install dexie

CDN 引入

<script src="https://unpkg.com/dexie@latest/dist/dexie.js"></script>

2. 创建数据库

// 创建或打开数据库
const db = new Dexie('MyDatabase');// 定义数据库模式和版本
db.version(1).stores({friends: '++id, name, age', // 主键是自增的id,索引有name和ageproducts: '++id, name, price'
});

3. 基本操作

添加数据

async function addFriend() {try {const id = await db.friends.add({name: '张三',age: 25,email: 'zhangsan@example.com'});console.log(`添加成功,ID: ${id}`);} catch (error) {console.error('添加失败:', error);}
}

查询数据

async function getFriends() {// 获取所有朋友const allFriends = await db.friends.toArray();console.log(allFriends);// 按条件查询const youngFriends = await db.friends.where('age').below(30).toArray();console.log(youngFriends);// 获取单个记录const friend = await db.friends.get(1);console.log(friend);
}

 更新数据

async function updateFriend() {try {const updated = await db.friends.update(1, {age: 26});if (updated) {console.log('更新成功');} else {console.log('未找到记录');}} catch (error) {console.error('更新失败:', error);}
}

删除数据

async function deleteFriend() {try {await db.friends.delete(1);console.log('删除成功');} catch (error) {console.error('删除失败:', error);}
}

4. 高级查询

使用 where() 方法

async function complexQuery() {// 年龄在20-30之间的朋友const friends = await db.friends.where('age').between(20, 30).toArray();// 名字以"张"开头的朋友const zhangFriends = await db.friends.where('name').startsWith('张').toArray();
}

使用 each() 方法迭代

async function iterateFriends() {await db.friends.each(friend => {console.log(friend.name);});
}

5. 事务处理

async function transactionExample() {await db.transaction('rw', db.friends, db.products, async () => {// 在这个事务中可以同时操作friends和products表await db.friends.add({name: '李四', age: 28});await db.products.add({name: '笔记本电脑', price: 5999});}).catch(error => {console.error('事务失败:', error);});
}

6. 数据库升级

当需要修改数据库结构时,可以增加版本号:

db.version(2).stores({friends: '++id, name, age, email', // 新增email字段products: '++id, name, price, stock' // 新增stock字段
});

7. 使用索引

async function useIndex() {// 使用name索引快速查询const friend = await db.friends.where('name').equals('张三').first();// 复合索引查询const friends = await db.friends.where(['name', 'age']).equals(['张三', 25]).toArray();
}

8. 错误处理

db.on('error', error => {console.error('数据库错误:', error);
});async function safeOperation() {try {await db.friends.add({name: '王五'});} catch (error) {console.error('操作失败:', error);}
}

9. 使用 Promise 和 async/await

async function demo() {try {// 添加数据await db.friends.add({name: '赵六', age: 30});// 查询数据const friends = await db.friends.toArray();console.log(friends);// 更新数据await db.friends.where('name').equals('赵六').modify({age: 31});} catch (error) {console.error('发生错误:', error);}
}

10. 关闭数据库

db.close();

总结

Dexie.js 大大简化了 IndexedDB 的使用,提供了更直观的 API 和强大的查询能力。通过本教程,你应该能够开始使用 Dexie.js 在浏览器中存储和操作数据了。更多高级功能可以参考 Dexie.js 官方文档。

 

http://www.jsqmd.com/news/48891/

相关文章:

  • 2025重庆好的留学机构
  • 2025新加坡留学中介排行
  • 2025苏州最好的留学机构在哪里啊
  • 2025深圳美国留学机构排名前十
  • 详细介绍:手机环境光自动亮度调节系统完整实现详解
  • 2025 年 11 月激光切割钢结构,大型钢结构,C 型钢结构厂家最新推荐,聚焦资质、案例、售后的五家机构深度解读!
  • Web 常见名词解释
  • 2025 年 11 月钢结构安装,钢结构设计,贰级资质钢结构,H 型钢结构最新推荐:聚焦资质、案例、售后的五家机构深度解读
  • AI与智能工具如何终结自由职业者发票困境
  • 2025年山东连栋玻璃温室公司权威推荐榜单:玻璃智能温室/玻璃连栋温室/玻璃温室设计源头公司精选
  • 2025 合同纠纷律师咨询最新推荐排行榜:股权债务 / 劳动仲裁 / 民商事诉讼顶尖法律顾问权威指南
  • 【数字逻辑】流水灯实战!红5秒/黄2秒/绿1秒精准控时(74HC161+74HC138完整便捷的方案+接线图)
  • windows11关闭系统自动更新
  • 2025年北京儿童孤独症谱系障碍培训权威推荐榜单:儿童高功能自闭症/儿童注意力培训机构/儿童注意力集训营培训精选
  • 2025 建筑工程施工总包施工团队最新推荐榜:聚焦质量管控与新锐势力,5 大维度权威甄选优质企业
  • 2025 最新聚合硫酸铁优质生产厂家最新推荐:覆盖多类型产品 解析实力厂商核心优势 助力采购方精准选品固态聚合硫酸铁 / 粉末聚合硫酸铁 / 硫酸亚铁公司推荐
  • linux lvm管理
  • AI SDK:重新定义 AI 应用开发
  • 2025年中频点焊机厂家权威推荐榜单:中频直流点焊机/中频交流点焊机/中频焊接设备源头厂家精选
  • 20232410 2025-2026-1 《网络与系统攻防技术》实验七实验报告
  • 主流开源JS地图框架选择
  • 管理千家经销商之困:医疗器械耗材生产企业的数字化破局之道
  • CH395Q INT脚变化说明
  • PHP 8.5 在性能、调试和运维方面的新特性
  • 洛谷 B3694:数列离散化 ← 数组 + sort + unique + lower_bound
  • 完整教程:2025年接单经验和软件外包平台一览
  • SpringCloud 常见面试题(三)
  • 4.Rocky Linux 网络配置 - 教程
  • 2025年最新国际货运代理公司实力推荐榜:全链路服务力到行业口碑深度评估
  • MySQL 8.4:未使用 mysql_native_password 却报插件未加载(Plugin mysql_native_password is not loaded)?