- IndexedDB 教程
- IndexedDB - 主頁
- IndexedDB - 簡介
- IndexedDB - 安裝
- IndexedDB - 連線
- IndexedDB - 物件儲存
- IndexedDB - 建立資料
- IndexedDB - 讀取資料
- IndexedDB - 更新資料
- IndexedDB - 刪除資料
- 使用 getAll() 函式
- IndexedDB - 索引
- IndexedDB - 範圍
- IndexedDB - 事務
- IndexedDB - 錯誤處理
- IndexedDB - 搜尋
- IndexedDB - 遊標
- IndexedDB - Promise 封裝
- IndexedDB - Ecmascript 繫結
- IndexedDB 有用資源
- IndexedDB - 快速指南
- IndexedDB - 有用資源
- IndexedDB - 討論
IndexedDB - 建立資料
在建立資料之前,我們需要了解如何傳輸資料。IndexedDB 開啟事務,並在每個事務中執行其各項資料操作。每個操作有四個步驟 -
- 獲取資料庫物件
- 在資料庫上開啟事務
- 在事務上開啟物件儲存
- 在物件儲存上操作
IndexedDB 中的操作 -
- 建立
- 讀取
- 更新
- 刪除
首先,要在資料庫中執行任何操作,我們需要開啟一個事務。開啟事務後,我們需要獲取所需的的物件儲存。這些物件儲存僅根據建立事務時提到的要求提供。然後可以稍後新增任何所需資料。
使用函式來執行給定操作(如果有)。例如,我們使用 add() 函式向資料庫中新增資料或新增新條目。
語法
下面是將資料建立到資料庫中的語法 -
ar request = objectStore.add(data);
我們可以透過使用 add() 或 put() 函式將資料新增到物件儲存中。
示例
在以下示例中,我們使用 JavaScript 中的 add() 方法將資料插入物件儲存 -
<!DOCTYPE html>
<html lang="en">
<head>
<title>creating data</title>
</head>
<body>
<script>
const dbName = "Database";
var request = indexedDB.open("Database", 2);
request.onupgradeneeded = event => {
var db = event.target.result;
var objectStore = db.createObjectStore("student",{ keyPath :"rollno" } );
};
request.onsuccess = event => {
document.write("Database opened successfully");
var db = event.target.result;
var transaction = db.transaction("student", "readwrite");
var objectStore = transaction.objectStore("student");
objectStore.add({ rollno: 160218737028, name: "jason", branch: "IT" });
objectStore.add({ rollno: 160218733028, name: "tarun", branch: "EEE" });
objectStore.add({ rollno: 160218732028, name: "lokesh", branch: "CSE" });
objectStore.add({ rollno: 160218737025, name: "abdul", branch: "IT" });
objectStore.add({ rollno: 160218736055, name: "palli", branch: "MECH" });
}
transaction.oncomplete = function () {
db.close();
};
</script>
</body>
</html>
輸出
0 160218732028
{rollno: 160218732028, name: 'lokesh', branch: 'CSE'}
1 160218733028
{rollno: 160218733028, name: 'tarun', branch: 'EEE'}
2 160218736055
{rollno: 160218736055, name: 'palli', branch: 'CSE'}
3 160218737025
{rollno: 160218737025, name: 'abdul', branch: 'IT'}
4 160218737028
{rollno: 160218737028, name: 'jason', branch: 'IT'}
廣告