// 打开数据库
const dbName = 'myDatabase';
const request = indexedDB.open(dbName, 1);
// 数据库被新建或升级时创建对象存储空间
request.onupgradeneeded = event => {
const db = event.target.result;
const objectStore = db.createObjectStore('customers', { keyPath: 'id' });
objectStore.createIndex('name', 'name', { unique: false });
objectStore.createIndex('email', 'email', { unique: true });
};
// 成功打开数据库
request.onsuccess = event => {
const db = event.target.result;
// 添加数据到对象存储空间
const transaction = db.transaction(['customers'], 'readwrite');
const objectStore = transaction.objectStore('customers');
objectStore.add({ id: 1, name: 'Alice', email: 'alice@example.com' });
objectStore.add({ id: 2, name: 'Bob', email: 'bob@example.com' });
transaction.oncomplete = () => {
console.log('Data added successfully');
};
// 获取数据
const getRequest = objectStore.get(1);
getRequest.onsuccess = () => {
console.log(getRequest.result);
};
// 通过索引获取数据
const index = objectStore.index('email');
const getEmailRequest = index.get('bob@example.com');
getEmailRequest.onsuccess = () => {
console.log(getEmailRequest.result);
};
};
// 打开数据库失败
request.onerror = event => {
console.log('Error opening database', event.target.error);
};