IndexedDB-增查示例

发布时间:2024年01月22日
// 打开数据库
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);
};
文章来源:https://blog.csdn.net/u013798595/article/details/135750707
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。