IndexedDB 是一个低级 API,用于在用户的浏览器中存储大量结构化数据。下面是增删改查(CRUD)操作的基本示例:
1. 打开数据库并创建对象存储
let db;
const request = indexedDB.open('myDatabase', 1);
request.onerror = function(event) {
console.error('Database error:', event.target.errorCode);
};
request.onsuccess = function(event) {
db = event.target.result;
console.log('Database opened successfully');
};
request.onupgradeneeded = function(event) {
db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
};
2. 添加数据(Create)
function addData(data) {
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.add(data);
request.onsuccess = function(event) {
console.log('Data added successfully');
};
request.onerror = function(event) {
console.error('Unable to add data:', event.target.errorCode);
};
}
// 示例数据
const newData = { id: 1, name: 'John Doe', email: 'john@example.com' };
addData(newData);
3. 读取数据(Read)
function readData(id) {
const transaction = db.transaction(['myObjectStore'], 'readonly');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.get(id);
request.onerror = function(event) {
console.error('Unable to retrieve data from database:', event.target.errorCode);
};
request.onsuccess = function(event) {
if (request.result) {
console.log('Data retrieved:', request.result);
} else {
console.log('No data found with ID:', id);
}
};
}
// 查询 ID 为 1 的数据
readData(1);
4. 更新数据(Update)
function updateData(data) {
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.put(data);
request.onsuccess = function(event) {
console.log('Data updated successfully');
};
request.onerror = function(event) {
console.error('Unable to update data:', event.target.errorCode);
};
}
// 更新 ID 为 1 的数据
const updatedData = { id: 1, name: 'Jane Doe', email: 'jane@example.com' };
updateData(updatedData);
5. 删除数据(Delete)
function deleteData(id) {
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const request = objectStore.delete(id);
request.onsuccess = function(event) {
console.log('Data deleted successfully');
};
request.onerror = function(event) {
console.error('Unable to delete data:', event.target.errorCode);
};
}
// 删除 ID 为 1 的数据
deleteData(1);
这些示例展示了如何在 IndexedDB 中进行基本的增删改查操作。请确保在实际应用中根据需要调整对象存储和索引的定义。
标签:function,transaction,const,示例,改查,objectStore,request,indexdb,event From: https://www.cnblogs.com/jocongmin/p/18595955