HTML5 IndexedDB Example

IndexedDB is a powerful client-side database API that allows you to store structured data in the browser. Here's how to add data to an IndexedDB database.

Setting Up IndexedDB

Before adding data, you need to open a database and create an object store:

let db;

// Open IndexedDB database
const request = indexedDB.open("EmployeeDB", 1);

request.onupgradeneeded = function(event) {
    db = event.target.result;
    const objectStore = db.createObjectStore("employee", { keyPath: "id" });
    console.log("Database setup complete");
};

request.onsuccess = function(event) {
    db = event.target.result;
    console.log("Database opened successfully");
};

request.onerror = function(event) {
    console.error("Database error:", event.target.errorCode);
};

Adding Data to IndexedDB

The following function demonstrates how to add employee data to the IndexedDB:

function addEmployee() {
    const transaction = db.transaction(["employee"], "readwrite");
    const objectStore = transaction.objectStore("employee");
    
    const employeeData = { 
        id: "001", 
        name: "Amit", 
        age: 28, 
        email: "demo1@example.com" 
    };
    
    const request = objectStore.add(employeeData);
    
    request.onsuccess = function(event) {
        console.log("Employee added successfully");
        alert("Amit has been added to your database.");
    };
    
    request.onerror = function(event) {
        console.error("Error adding employee:", event.target.error);
        alert("Unable to add data. Employee may already exist!");
    };
}

// Call the function (assuming database is already opened)
setTimeout(() => addEmployee(), 1000);

Complete Working Example

Here's a complete example that opens the database and adds multiple employees:

let db;

// Sample employee data
const employeeData = [
    { id: "001", name: "Amit", age: 28, email: "amit@example.com" },
    { id: "002", name: "Sarah", age: 32, email: "sarah@example.com" },
    { id: "003", name: "John", age: 25, email: "john@example.com" }
];

// Open database
const dbRequest = indexedDB.open("CompanyDB", 1);

dbRequest.onupgradeneeded = function(event) {
    db = event.target.result;
    const objectStore = db.createObjectStore("employee", { keyPath: "id" });
    console.log("Database and object store created");
};

dbRequest.onsuccess = function(event) {
    db = event.target.result;
    console.log("Database opened successfully");
    
    // Add all employees
    addAllEmployees();
};

function addAllEmployees() {
    const transaction = db.transaction(["employee"], "readwrite");
    const objectStore = transaction.objectStore("employee");
    
    employeeData.forEach(employee => {
        const request = objectStore.add(employee);
        
        request.onsuccess = function() {
            console.log(`Added employee: ${employee.name}`);
        };
        
        request.onerror = function() {
            console.log(`Failed to add employee: ${employee.name}`);
        };
    });
}
Database and object store created
Database opened successfully
Added employee: Amit
Added employee: Sarah
Added employee: John

Key Points

  • Transaction: Use "readwrite" mode for adding data
  • Object Store: Specify the store name when creating transactions
  • Key Path: The "id" field serves as the unique identifier
  • Error Handling: Always handle both success and error events

Conclusion

IndexedDB's add() method provides a reliable way to insert structured data into the browser's local database. Always handle success and error cases for robust data management.

Updated on: 2026-03-15T23:18:59+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements