本文基本仅做个人简单学习记录;
相关TS类型:
-
IDBDatabase:open成功后的 result 为 IDBDatabase类型 > idb.result;
-
transaction: transaction(storeNames: string | string[], mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction;
-
IDBTransaction:
-
IDBObjectStore: 调用 IDBTransaction类型下面的该函数 objectStore(name: string): IDBObjectStore 后返回的实例就是IDBObjectStore; 该类型的实例就是专门对数据库进行增删改查的了;
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title></head><body><script>console.log("同步测试1");console.log(indexedDB);const idb = indexedDB.open("db_name_1"); // MyTestDatabaselet db; // 连接成功后将数据库实例绑定到该变量上;console.log(idb);idb.onupgradeneeded = function (event) {console.log("如果数据库不存在或版本号较低,就会触发 onupgradeneeded 事件");// 通常情况下,在这执行数据库结构的变更,比如创建对象存储空间、设置索引等操作。// 创建对象存储空间const objectStore = db.createObjectStore("customers", {keyPath: "id",});};idb.onerror = (event) => {// 错误事件遵循冒泡机制。// 错误事件都是针对产生这些错误的请求的,然后事件冒泡到事务,然后最终到达数据库对象。document.body.innerHTML += "<li>Error loading database.</li>";console.log(event, "失败建立");};idb.onsuccess = (event) => {// 保存 IDBDatabase 接口db = idb.result;db.onerror = (event) => {// 可以仅针对此数据库请求的所有错误的通用错误处理器!console.error(`数据库错误:`, event.target);};document.body.innerHTML += "<li>成功</li>";setData();};console.log("同步测试2");function setData() {// 添加数据到数据库const transaction = db.transaction(["customers"], "readwrite");const objectStore = transaction.objectStore("customers");const customer = { id: 1, name: "Alice", email: "alice@example.com" };const addRequest = objectStore.add(customer);addRequest.onerror = function (event) {// getData(1);putData();};addRequest.onsuccess = function (event) {console.log("Data added successfully");getData(2);};}function putData() {const transaction = db.transaction(["customers"], "readwrite");const objectStore = transaction.objectStore("customers");const newData = {id: 1,name: "修改后的值" + Math.random(),}console.log("修改值:", newData);const putRes = objectStore.put(newData);putRes.onsuccess = function (event) {getData(3);};}function getData(source) {console.log(source, "来源");// 检索数据const getTransaction = db.transaction(["customers"], "readonly");const getObjectStore = getTransaction.objectStore("customers");const getRequest = getObjectStore.get(1);getRequest.onsuccess = function (event) {const result = getRequest.result;console.log("Retrieved data:", result);// 关闭数据库连接db.close();};}</script></body>
</html>