HTML Basic
HTML Entity
- HTML Entity
- HTML Alphabet Entity
- HTML Arrow Entity
- HTML Currency Entity
- HTML Math Entity
- HTML Number Entity
- HTML Punctuation Entity
- HTML Symbol Entity
HTML IndexedDB
HTML Reference
HTML IndexedDB Insert
Photo Credit to CodeToFun
How to insert in IndexedDB?
To insert data into IndexedDB, follow these steps:
- Open a connection to the database using
indexedDB.open('databaseName', version)
- In the onupgradeneeded event, create an object store using
createObjectStore('objectStoreName')
. - In the onsuccess event, start a transaction with
transaction('objectStoreName', 'readwrite')
. - Access the object store using
objectStore('objectStoreName')
. - Use the
add()
method to insert data into the object store.
📄 Example
The following is a simple example to `Insert a data in IndexedDB`.
<!DOCTYPE html>
<html>
<head>
<title>IndexedDB Insert Example</title>
<script>
// Open a connection to the database
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction('myObjectStore', 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
const data = { id: 1, name: 'John Doe', age: 25 };
const request = objectStore.add(data);
request.onsuccess = () => {
console.log('Data inserted successfully.');
};
transaction.oncomplete = () => {
console.log('Transaction completed.');
db.close();
};
};
request.onerror = (event) => {
console.error('Error opening database:', event.target.error);
};
</script>
</head>
<body>
<!-- HTML content -->
</body>
</html>
In this example, we have an HTML file that includes a script section where the IndexedDB operations are performed.
The script starts by opening a connection to the database named myDatabase and creating an object store named myObjectStore. Then, it starts a transaction and inserts data { id: 1, name: 'John Doe', age: 25 } into the object store using the add()
method.
When running this HTML file in a browser, the script will execute and perform the IndexedDB operations accordingly. You can check the browser's developer console to view the output and any potential errors.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (HTML IndexedDB Insert) please comment here. I will help you immediately.