前端小白对IndexDB的简单理解

229 阅读3分钟

什么是IndexedDB

IndexedDB是一种Web API,它提供了一种在Web浏览器中存储和检索大量结构化数据的方式。它是一个本地的、事务性的、非关系型的数据库,在Web浏览器中使用。

IndexedDB的目的是提供一个高效的方式来存储和检索大量数据,而不会对Web应用程序的性能产生负面影响。IndexedDB使用JavaScript API来访问数据库,并且在Web应用程序中采用结构化数据来进行存储和检索,所以它可以存储大量的数据,并且可以在不影响Web应用程序性能的情况下高效地检索和更新这些数据,这使得IndexedDB成为一种非常强大的存储和检索数据的方式,特别是在需要存储和检索大量数据的情况下。

为什么是IndexDB

在浏览器中,我们通常需要存储一些并不小的数据,比如用户的登录信息、浏览记录、购物车数据等等,而IndexedDB就是这样一种解决我们需要存储大量数据的方式,它可以帮助我们快速、高效地存储和检索数据。相比于传统的cookie和localStorage,IndexedDB有以下优势:

  1. 存储容量更大:cookie和localStorage的存储容量有限,而IndexedDB可以存储更大的数据量,可以存储数百兆甚至数百G的数据。
  2. 支持事务:IndexedDB支持事务,可以保证数据的一致性和完整性。
  3. 支持索引:IndexedDB支持索引,可以快速地检索数据。
  4. 支持异步操作:IndexedDB支持异步操作,可以在后台执行操作,不会阻塞主线程,提高了性能。

IndexDB的简单使用

IndexDb的初始化工作

const request = window.indexedDB.open('testDB', 1);
let db;
//打开成功--如果数据库打开成功,则会执行该回调函数
request.onsuccess = (e) => {
    db = e.target.result;
    console.log('数据库打开成功!');
}
//打开失败--如果数据库打开失败,则会执行该回调函数
request.onerror = (e) => {
    console.log('数据库打开失败!');
}
//版本更新--如果数据库版本发生变化或者是首次创建数据库,则会执行该回调函数
request.onupgradeneeded = (e) => {
    db = e.target.result;
    console.log('数据库版本已变更:', db.version);
    // 创建一个名为students的对象仓库,并指定id为主键
    const objectStore = db.createObjectStore('students', { keyPath: 'id' });
    // 在对象仓库中添加一个名为name的索引
    objectStore.createIndex('name', 'name', { unique: false });
}

屏幕截图 2023-04-22 233605.png

屏幕截图 2023-04-22 234034.png 向该数据库增加一条数据

//增加数据
function AddData() {
    const request = window.indexedDB.open('testDB', 1);
    let db;
    //打开成功--如果数据库打开成功,则会执行该回调函数
    request.onsuccess = (e) => {
        db = e.target.result;
        // 打开一个读写事务,从仓库中获取对象仓库
        const transaction = db.transaction(['students'], 'readwrite');
        const objectStore = transaction.objectStore('students');
        //一个对象数据
        const student = {
            id: 1,
            name: 'Tom',
            age: 18,
        };
        //向仓库中增加数据
        const requestAdd = objectStore.add(student);
        //添加成功
        requestAdd.onsuccess = (event) => {
            console.log('添加数据成功!');
        };
        //添加失败
        requestAdd.onerror = (event) => {
            console.log('添加数据失败!');
        };
    }
    //打开失败--如果数据库打开失败,则会执行该回调函数
    request.onerror = (e) => {
        console.log('数据库打开失败!');
    }
}

屏幕截图 2023-04-22 233825.png 屏幕截图 2023-04-22 233933.png

删除、查询、修改也和增加差不多,就是语句的不同

根据id,在仓库中查询数据

const requestAdd = objectStore.get(id);

向仓库中修改数据

const requestAdd = objectStore.put(student);

根据id,向仓库中删除数据

const requestAdd = objectStore.delete(id);

这就是差不多笔者对IndexDB的简单理解和学习。