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

JS如何操作IndexedDB

IndexedDB 是一个在浏览器中存储大量结构化数据的低级 API,它允许你存储和检索 JavaScript 对象,并支持索引。由于其异步特性,所有操作都通过**事务(Transaction)**来完成。

以下例子给出了如何对IndexedDB进行增删改查操作。Copy即可直接使用。

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>IndexedDB 操作演示</title><style>* {box-sizing: border-box;margin: 0;padding: 0;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}body {background-color: #f5f7fa;color: #333;line-height: 1.6;padding: 20px;}.container {max-width: 1000px;margin: 0 auto;background: white;border-radius: 10px;box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);padding: 30px;}h1 {text-align: center;margin-bottom: 30px;color: #2c3e50;}.description {text-align: center;margin-bottom: 30px;color: #7f8c8d;}.panel {display: flex;flex-wrap: wrap;gap: 20px;margin-bottom: 30px;}.controls, .form {flex: 1;min-width: 300px;background: #f8f9fa;padding: 20px;border-radius: 8px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);}h2 {margin-bottom: 15px;color: #3498db;font-size: 1.2rem;}button {background: #3498db;color: white;border: none;padding: 10px 15px;border-radius: 5px;cursor: pointer;margin: 5px;transition: background 0.3s;font-size: 0.9rem;}button:hover {background: #2980b9;}.form-group {margin-bottom: 15px;}label {display: block;margin-bottom: 5px;font-weight: 500;}input {width: 100%;padding: 10px;border: 1px solid #ddd;border-radius: 5px;}.data-display {background: #f8f9fa;padding: 20px;border-radius: 8px;box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);margin-top: 20px;}table {width: 100%;border-collapse: collapse;margin-top: 15px;}th, td {padding: 12px 15px;text-align: left;border-bottom: 1px solid #ddd;}th {background-color: #3498db;color: white;}tr:hover {background-color: #f1f1f1;}.status {margin-top: 20px;padding: 15px;border-radius: 5px;background: #e8f4fc;border-left: 4px solid #3498db;}.error {background: #fde8e8;border-left: 4px solid #e74c3c;}.success {background: #e8f8ef;border-left: 4px solid #2ecc71;}.action-buttons {display: flex;gap: 5px;}.btn-edit {background: #f39c12;}.btn-edit:hover {background: #e67e22;}.btn-delete {background: #e74c3c;}.btn-delete:hover {background: #c0392b;}@media (max-width: 768px) {.panel {flex-direction: column;}.controls, .form {min-width: 100%;}}</style>
</head>
<body><div class="container"><h1>IndexedDB 增删改查操作演示</h1><p class="description">使用此界面来学习如何对浏览器的IndexedDB进行增删改查操作</p><div class="panel"><div class="controls"><h2>数据库操作</h2><button id="openDB">打开数据库</button><button id="clearDB">清空数据库</button><button id="addSample">添加示例数据</button><button id="getAll">获取所有数据</button><div class="status" id="dbStatus">准备就绪...</div></div><div class="form"><h2>数据操作</h2><div class="form-group"><label for="userId">ID:</label><input type="text" id="userId" placeholder="输入用户ID"></div><div class="form-group"><label for="userName">姓名:</label><input type="text" id="userName" placeholder="输入姓名"></div><div class="form-group"><label for="userEmail">邮箱:</label><input type="text" id="userEmail" placeholder="输入邮箱"></div><div class="form-group"><label for="userAge">年龄:</label><input type="number" id="userAge" placeholder="输入年龄"></div><button id="addData">添加数据</button><button id="updateData">更新数据</button><button id="getData">查询数据</button><button id="deleteData">删除数据</button></div></div><div class="data-display"><h2>数据列表</h2><div id="dataList">暂无数据</div></div></div><script>// 数据库变量let db;const dbName = "UserDB";const storeName = "users";const dbVersion = 1;// DOM元素const dbStatus = document.getElementById('dbStatus');const dataList = document.getElementById('dataList');// 打开数据库document.getElementById('openDB').addEventListener('click', function() {const request = indexedDB.open(dbName, dbVersion);request.onerror = function(event) {updateStatus("打开数据库失败: " + event.target.error, 'error');};request.onsuccess = function(event) {db = event.target.result;updateStatus("数据库打开成功", 'success');getAllData();};request.onupgradeneeded = function(event) {db = event.target.result;updateStatus("数据库升级中...");// 创建对象存储空间(表)if (!db.objectStoreNames.contains(storeName)) {const objectStore = db.createObjectStore(storeName, { keyPath: "id" });// 创建索引objectStore.createIndex("name", "name", { unique: false });objectStore.createIndex("email", "email", { unique: true });objectStore.createIndex("age", "age", { unique: false });updateStatus("对象存储空间创建成功");}};});// 添加数据document.getElementById('addData').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const id = document.getElementById('userId').value;const name = document.getElementById('userName').value;const email = document.getElementById('userEmail').value;const age = parseInt(document.getElementById('userAge').value);if (!id || !name || !email || !age) {updateStatus("请填写所有字段", 'error');return;}const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.add({id: id,name: name,email: email,age: age});request.onsuccess = function() {updateStatus("数据添加成功", 'success');clearForm();getAllData();};request.onerror = function(event) {if (request.error.name === "ConstraintError") {updateStatus("ID或邮箱已存在", 'error');} else {updateStatus("添加数据失败: " + event.target.error, 'error');}};});// 查询数据document.getElementById('getData').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const id = document.getElementById('userId').value;if (!id) {updateStatus("请输入要查询的ID", 'error');return;}const transaction = db.transaction([storeName], "readonly");const objectStore = transaction.objectStore(storeName);const request = objectStore.get(id);request.onsuccess = function() {if (request.result) {const user = request.result;document.getElementById('userName').value = user.name;document.getElementById('userEmail').value = user.email;document.getElementById('userAge').value = user.age;updateStatus("数据查询成功", 'success');} else {updateStatus("未找到该ID的数据", 'error');}};request.onerror = function(event) {updateStatus("查询数据失败: " + event.target.error, 'error');};});// 更新数据document.getElementById('updateData').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const id = document.getElementById('userId').value;const name = document.getElementById('userName').value;const email = document.getElementById('userEmail').value;const age = parseInt(document.getElementById('userAge').value);if (!id || !name || !email || !age) {updateStatus("请填写所有字段", 'error');return;}const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.put({id: id,name: name,email: email,age: age});request.onsuccess = function() {updateStatus("数据更新成功", 'success');clearForm();getAllData();};request.onerror = function(event) {updateStatus("更新数据失败: " + event.target.error, 'error');};});// 删除数据document.getElementById('deleteData').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const id = document.getElementById('userId').value;if (!id) {updateStatus("请输入要删除的ID", 'error');return;}const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.delete(id);request.onsuccess = function() {updateStatus("数据删除成功", 'success');clearForm();getAllData();};request.onerror = function(event) {updateStatus("删除数据失败: " + event.target.error, 'error');};});// 获取所有数据document.getElementById('getAll').addEventListener('click', getAllData);// 添加示例数据document.getElementById('addSample').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const sampleData = [{ id: "1", name: "张三", email: "zhangsan@example.com", age: 25 },{ id: "2", name: "李四", email: "lisi@example.com", age: 30 },{ id: "3", name: "王五", email: "wangwu@example.com", age: 28 }];const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);let addedCount = 0;let errorCount = 0;sampleData.forEach(function(user) {const request = objectStore.add(user);request.onsuccess = function() {addedCount++;if (addedCount + errorCount === sampleData.length) {updateStatus(`示例数据添加完成: 成功 ${addedCount} 条, 失败 ${errorCount} 条`, errorCount > 0 ? 'error' : 'success');getAllData();}};request.onerror = function() {errorCount++;if (addedCount + errorCount === sampleData.length) {updateStatus(`示例数据添加完成: 成功 ${addedCount} 条, 失败 ${errorCount} 条`, errorCount > 0 ? 'error' : 'success');getAllData();}};});});// 清空数据库document.getElementById('clearDB').addEventListener('click', function() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.clear();request.onsuccess = function() {updateStatus("数据库已清空", 'success');dataList.innerHTML = "暂无数据";};request.onerror = function(event) {updateStatus("清空数据库失败: " + event.target.error, 'error');};});// 获取所有数据并显示function getAllData() {if (!db) {updateStatus("请先打开数据库", 'error');return;}const transaction = db.transaction([storeName], "readonly");const objectStore = transaction.objectStore(storeName);const request = objectStore.getAll();request.onsuccess = function() {const users = request.result;displayData(users);};request.onerror = function(event) {updateStatus("获取数据失败: " + event.target.error, 'error');};}// 显示数据function displayData(users) {if (users.length === 0) {dataList.innerHTML = "暂无数据";return;}let html = '<table><thead><tr><th>ID</th><th>姓名</th><th>邮箱</th><th>年龄</th><th>操作</th></tr></thead><tbody>';users.forEach(function(user) {html += `<tr><td>${user.id}</td><td>${user.name}</td><td>${user.email}</td><td>${user.age}</td><td class="action-buttons"><button class="btn-edit" onclick="loadUserData('${user.id}')">编辑</button><button class="btn-delete" onclick="deleteUser('${user.id}')">删除</button></td></tr>`;});html += '</tbody></table>';dataList.innerHTML = html;}// 加载用户数据到表单function loadUserData(id) {if (!db) {updateStatus("请先打开数据库", 'error');return;}const transaction = db.transaction([storeName], "readonly");const objectStore = transaction.objectStore(storeName);const request = objectStore.get(id);request.onsuccess = function() {if (request.result) {const user = request.result;document.getElementById('userId').value = user.id;document.getElementById('userName').value = user.name;document.getElementById('userEmail').value = user.email;document.getElementById('userAge').value = user.age;updateStatus("数据已加载到表单", 'success');}};}// 删除用户function deleteUser(id) {if (!db) {updateStatus("请先打开数据库", 'error');return;}const transaction = db.transaction([storeName], "readwrite");const objectStore = transaction.objectStore(storeName);const request = objectStore.delete(id);request.onsuccess = function() {updateStatus("数据删除成功", 'success');getAllData();};request.onerror = function(event) {updateStatus("删除数据失败: " + event.target.error, 'error');};}// 更新状态function updateStatus(message, type = '') {dbStatus.textContent = message;dbStatus.className = 'status';if (type) {dbStatus.classList.add(type);}}// 清空表单function clearForm() {document.getElementById('userId').value = '';document.getElementById('userName').value = '';document.getElementById('userEmail').value = '';document.getElementById('userAge').value = '';}// 初始化:自动打开数据库window.onload = function() {document.getElementById('openDB').click();};</script>
</body>
</html>

http://www.dtcms.com/a/548781.html

相关文章:

  • 网站正在维护中wordpress 评分
  • Kafka关闭日志,启动一直打印日志
  • 搬家网站建设思路荆门哪里有专门做企业网站的
  • 前后端分离
  • curl开发常用方法总结
  • rust实战:基础框架Rust + Tauri Windows 桌面应用开发文档
  • knife4j在配置文件(xml文件)的配置错误
  • Java的多线程——多线程(二)
  • 小企业也能用AI?低成本智能转型实战案例
  • ros2 播放 ros1 bag
  • 网页设计做一个网站设计之家官方网站
  • 基于STM32单片机 + DeepSeek-OCR 的智能文档扫描助手设计与实现
  • 微信小程序如何传递参数
  • 【数据结构】:数组及特殊矩阵
  • 记录一下微信小程序里使用SSE
  • API 接口安全:用 JWT + Refresh Token 解决 Token 过期与身份伪造问题
  • 云手机搬砖 高效采集资源
  • GitHub Actions CI/CD 自动化部署完全指南
  • Fastlane 结合 开心上架 命令行版本实现跨平台上传发布 iOS App
  • 广东营销网站建设服务公司军事信息化建设网站
  • Go Web 编程快速入门 14 - 性能优化与最佳实践:Go应用性能分析、内存管理、并发编程最佳实践
  • LeetCode每日一题——合并两个有序链表
  • 丽江市建设局官方网站门户网站开发需要多少钱
  • 边缘计算中评估多模态分类任务的延迟
  • 11.9.16.Filter(过滤器)
  • 光储充微电网能量管理系统:构建绿色、高效、安全的能源未来
  • MR30分布式IO在自动上料机的应用
  • 有些网站为什么可以做资讯建站工具交流
  • .NET周刊【10月第2期 2025-10-12】
  • 自动化文献引用和交叉引用高亮显示:Word VBA宏解决方案