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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)
  • Liquibase: Database Change Management and Automated Deployments

Trending

  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • Exactly-Once Processing: Myth vs Reality
  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  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.4K 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

  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • Master-Class: Understanding Database Replication (Single, Multi, and Leaderless)
  • Liquibase: Database Change Management and Automated Deployments

Partner Resources

×

Comments

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

  • 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