IndexedDB – Creating Data
Before creating data we need to know how data is transferred. IndexedDB opens transactions and each of its data operations are carried out inside each of these transactions. Each operation has four steps −
- Get database object
- Open transaction on the database
- Open object store on the transaction
- Operate on the object store
Operations in IndexedDB are −
- create
- read
- update
- delete
Firstly, to perform any operation in our database, we need to open a transaction. After a transaction is opened, we need to get the object store we require. These object stores are provided only according the requirements mentioned when the transaction is created. Then whatever data that is needed can be added later.
Functions are used to perform the given operation (if any). For example, we use the add() function to add data into the database or to add a new entry.
Syntax
Following is the syntax of creating data into a database −
ar request = objectStore.add(data);
We can add data to an object store by using the add() or put() function.
Example
In the following example, we are inserting data into the object store using the add() method in JavaScript −
<!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>
Output
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''}