Google IndexedDB client stores data

IndexedDB has the following key features:

1. Store large amounts of data: IndexedDB can store large amounts of data, such as storing local cache for offline applications or storing large amounts of data for online applications.

2. Structured data: IndexedDB uses object stores to store data, where each object has a key to uniquely identify them. Developers can create different storage spaces as needed and define the structure of objects in each storage space.

3. Queries and operations: Using IndexedDB, developers can perform a variety of queries and operations, including adding, updating, deleting, and retrieving data. You can use indexes to improve query efficiency so that you can access and search specific data faster.

4. Transaction support: IndexedDB supports transaction mechanism, which means that data consistency can be maintained in a series of operations. A set of operations in a transaction must either be successfully committed or rolled back to ensure data integrity and consistency.

Code example

The following is a simple sample code using IndexedDB, demonstrating how to create a storage space, add data, and query data:

// 打开或创建 IndexedDB 数据库
var request = indexedDB.open("myDatabase", 1);

request.onerror = function(event) {
  console.log("打开数据库错误");
};

request.onupgradeneeded = function(event) {
  var db = event.target.result;

  // 创建一个名为 "customers" 的存储空间,并定义一个键路径
  var objectStore = db.createObjectStore("customers", { keyPath: "id" });

  // 在存储空间中创建一个索引
  objectStore.createIndex("name", "name", { unique: false });

  // 数据填充
  objectStore.add({ id: 1, name: "Alice", email: "[email protected]" });
  objectStore.add({ id: 2, name: "Bob", email: "[email protected]" });
};

request.onsuccess = function(event) {
  var db = event.target.result;

  // 开始一个只读事务
  var transaction = db.transaction(["customers"], "readonly");

  // 获取存储空间对象
  var objectStore = transaction.objectStore("customers");

  // 使用索引查询数据
  var index = objectStore.index("name");
  var request = index.get("Alice");

  request.onsuccess = function(event) {
    var customer = event.target.result;
    console.log(customer);
  };

  transaction.oncomplete = function(event) {
    db.close();
  };
};

This sample code shows how to open or create an IndexedDB database named "myDatabase". In the "onupgradeneeded" event handler, we create a storage called "customers" and add some data to it. Then, in the "onsuccess" event handler, we perform a read-only transaction and use the index to query the customer data named "Alice" and print the results to the console. Finally, in the transaction's "oncomplete" event handler, we close the database connection.

Guess you like

Origin blog.csdn.net/beiback/article/details/132644110