DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Trustworthy Is Big Data?
  • Fixing Common Oracle Database Problems
  • How to Restore a Transaction Log Backup in SQL Server
  • Why I Built the Ultimate Text Comparison Tool (And Why You Should Try It)

Trending

  • Automatic Code Transformation With OpenRewrite
  • Java Virtual Threads and Scaling
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  • A Complete Guide to Modern AI Developer Tools
  1. DZone
  2. Data Engineering
  3. Databases
  4. CRUD Operations in IndexedDB Using JsStore

CRUD Operations in IndexedDB Using JsStore

Many developers avoid IndexedDB because it can be pretty complicated to use. Enter: the JsStore library for performing CRUD operations and SQL queries in IndexedDB.

By 
Uday Kumar Choudhary user avatar
Uday Kumar Choudhary
·
Jan. 16, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
8.1K Views

Join the DZone community and get the full member experience.

Join For Free

IndexedDB is a database technology to store data in browsers. The problem is that it is too complex, even for simple cases, so most developers don't use it.

I was struggling with the same situation but I had to use it in one of my projects. I found an awesome library called JsStore that makes IndexedDB look like SQL and simpler than you can imagine. Then, I thought about efficiency and all. I researched a little and found that it executes the query in the web worker and handles everything for you.

In this article, I am going to explain how to do CRUD operations in IndexedDB.

Installation

The most efficient way to use JsStore is to download the script directly because it needs to be executed inside the web worker for maximum performance. The files are in the dist folder.

Now, let's include the file on our HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Crud Demo using jsstore</title>
    <script src="JsStore-1.4.0.min.js"></script>
</head>
<body>

</body>
</html>

Creating a Database

JsStore follows the SQL approach to create a database (A database consists of tables and a table consists of columns).

Let's see how to create a database schema in JsStore.

  • A database is an object that has a list of tables.

  • A table is an object that has a list of columns.

  • A column is an object that contains many options like primary key, autoincrement, default, etc., just like options in SQL.

var DbName ='JsStore_Demo';
function getDbSchema() {
  var TblProduct = {
    Name: 'Product',
    Columns: [
      {
          Name: 'Id',
          PrimaryKey: true,
          AutoIncrement: true
      }, 
      {
          Name: 'ItemName',
          NotNull: true
      }, 
      {
          Name: 'Price',
          NotNull: true,
          DataType: 'number'
      }, 
      {
          Name: 'Quantity',
          NotNull: true,
          DataType: 'number'
      }
    ]
  };
  var Db = {
      Name: DbName,
      Tables: [TblProduct]
  }
  return Db;
}

The above code is a database schema. We need to create the database with the above schema.

var Connection = new JsStore.Instance();
function initJsStore() {
  JsStore.isDbExist(DbName, function(isExist) {
    if (isExist) {
      Connection.openDb(DbName);
    } else {
      var Database = getDbSchema();
      Connection.createDb(Database);
    }
  }, function(err) {
    console.error(err);
  })
}

Now, the database is created in the browser. You can verify this by opening the developer tools.

Image title

Insert Data

JsStore provides the Insert API for inserting data.

var Value = {
  ItemName:'Blue Jeans',
  Price: 2000,
  Quantity:1000
}
// since Id is autoincrement column, so the value will be automatically generated.
Connection.insert({
  Into: 'Product',
  Values: [Value]
  OnSuccess: function(rowsInserted) {
    if (rowsInserted > 0) {
      alert('successfully added');
    }
  },
  OnError: function(err) {
    console.log(err);
  }
});
}

You can also insert multiple values at a time. There are multiple options if you want to insert a large amount of data at once.

  • Tutorial on Insert (you can use SkipDataCheck for not checking and manipulating data. This will speed up the insert).

  • Tutorial on Bulk Insert.

Read Data

JsStore provides the Select API for reading data.

Let's say that I want to execute the SQL query select * from product where Id=5.

Connection.select({
    From: 'Product',
    Where: {
      Id: 5
    },
    OnSuccess: function(results) {
      alert(results.length + 'record found');
    },
    OnError: function(err) {
      console.log(err);
    }
});

Update Data

Let's say that I want to execute the SQL query update product set quantity=200 where itemname like '%black%'.

Connection.update({
  In: 'Product',
  Where: {
    ItemName: {
      Like:'%black%'
    }
  },
  Set: {
    Quantity: 2000
  },
  OnSuccess: function(rowsUpdated) {
    alert(rowsUpdated + ' rows updated')
  },
    OnError: function(err) {
      console.log(err);
      alert(err.Message);
    }
});

Delete Data

Let's say that I want to execute the SQL query delete from product where id=10.

Connection.delete({
    From: 'Product',
    Where: {
      Id: 10
    },
    OnSuccess: function(rowsDeleted) {
      alert(rowsDeleted + ' record deleted');
    },
    OnError: function(err) {
      console.log(err);
      alert(err.Message);
    }
});

You can execute almost all types of SQL queries in IndexedDB using JsStore. Isn't cool it?

Thanks for reading!

Database

Published at DZone with permission of Uday Kumar Choudhary. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Trustworthy Is Big Data?
  • Fixing Common Oracle Database Problems
  • How to Restore a Transaction Log Backup in SQL Server
  • Why I Built the Ultimate Text Comparison Tool (And Why You Should Try It)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!