IndexedDB 使用实例
时间: 2023-06-28 20:10:07 浏览: 80
IndexedDB 是一种浏览器内置的 NoSQL 数据库,允许您在浏览器中存储和检索数据。下面是一个基本的 IndexedDB 示例:
```javascript
// 打开 IndexedDB 数据库
var request = window.indexedDB.open("myDatabase", 1);
// 处理成功和失败事件
request.onerror = function(event) {
console.log("Database error: " + event.target.errorCode);
};
request.onsuccess = function(event) {
console.log("Database opened successfully");
var db = event.target.result;
// 添加数据到数据库
var transaction = db.transaction(["customers"], "readwrite");
var objectStore = transaction.objectStore("customers");
var customer = { name: "John", email: "john@example.com" };
var request = objectStore.add(customer);
request.onsuccess = function(event) {
console.log("Customer added to database");
};
// 从数据库中检索数据
var transaction = db.transaction(["customers"], "readonly");
var objectStore = transaction.objectStore("customers");
var request = objectStore.get(1);
request.onerror = function(event) {
console.log("Error retrieving customer");
};
request.onsuccess = function(event) {
var customer = event.target.result;
console.log("Retrieved customer: " + customer.name);
};
};
// 创建数据库架构
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("customers", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("name", "name", { unique: false });
objectStore.createIndex("email", "email", { unique: true });
};
```
这段代码会创建一个名为 "myDatabase" 的 IndexedDB 数据库,其中包含一个名为 "customers" 的对象仓库,用于存储客户数据。该代码还演示了如何向数据库添加数据、从数据库检索数据以及如何创建对象仓库和索引。
阅读全文