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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Should Developers Switch From SQLite to DuckDB?
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance

Trending

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Batching Strategies: Throughput vs Latency in Practice
  • How to Build Your Own AI SRE From Scratch
  • Why Kotlin or Java Is the Wrong Question For Enterprises

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jan. 16, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Should Developers Switch From SQLite to DuckDB?
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • PostgreSQL vs Oracle: When Higher Cost Means Better Performance

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook