DEV Community

Cover image for Working with Databases in JavaScript: SQL and NoSQL
Rowsan Ali
Rowsan Ali

Posted on

16

Working with Databases in JavaScript: SQL and NoSQL

In the world of web development, working with databases is a fundamental skill. Databases store, organize, and retrieve data, making them an integral part of building dynamic web applications. JavaScript, one of the most popular programming languages for web development, can be used to interact with databases, both SQL and NoSQL. In this blog post, we'll explore the concepts and code examples of working with databases in JavaScript.
Want to learn more Follow me on X

Understanding Databases

SQL Databases

Structured Query Language (SQL) databases are relational databases that use tables to store data. Popular SQL databases include MySQL, PostgreSQL, and SQLite. JavaScript can interact with these databases using various libraries and drivers.

NoSQL Databases

NoSQL databases, on the other hand, are non-relational databases that store data in various formats like JSON, BSON, or XML. Examples of NoSQL databases include MongoDB, CouchDB, and Redis. JavaScript can communicate with NoSQL databases using dedicated libraries and drivers.

Setting up a SQL Database

For this example, let's use SQLite, a lightweight SQL database. First, install the sqlite3 package:

npm install sqlite3
Enter fullscreen mode Exit fullscreen mode

Next, create a JavaScript file (e.g., sql-database.js) to interact with the database:

const sqlite3 = require('sqlite3').verbose();

// Create a database connection
const db = new sqlite3.Database('mydb.sqlite');

// Create a table
db.serialize(() => {
  db.run('CREATE TABLE IF NOT EXISTS users (id INT, name TEXT)');
});

// Insert data
const stmt = db.prepare('INSERT INTO users VALUES (?, ?)');
stmt.run(1, 'Alice');
stmt.run(2, 'Bob');
stmt.finalize();

// Query data
db.each('SELECT id, name FROM users', (err, row) => {
  if (err) {
    console.error(err.message);
  }
  console.log(`${row.id} - ${row.name}`);
});

// Close the database connection
db.close();
Enter fullscreen mode Exit fullscreen mode

Working with a NoSQL Database

Let's use MongoDB as an example of a NoSQL database. First, install the mongodb package:

npm install mongodb
Enter fullscreen mode Exit fullscreen mode

Create a JavaScript file (e.g., nosql-database.js) to interact with MongoDB:

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const dbName = 'mydb';

// Connect to MongoDB
MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
  if (err) throw err;

  const db = client.db(dbName);

  // Create a collection
  const collection = db.collection('documents');

  // Insert a document
  collection.insertOne({ id: 1, name: 'Alice' }, (err, result) => {
    if (err) throw err;
    console.log('Document inserted');
  });

  // Find documents
  collection.find({}).toArray((err, documents) => {
    if (err) throw err;
    console.log(documents);
  });

  // Close the MongoDB connection
  client.close();
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

Working with databases in JavaScript is a crucial aspect of web development. Whether you choose SQL or NoSQL, JavaScript provides the tools and libraries needed to interact with a wide variety of databases. The examples provided here are just the tip of the iceberg, but they should give you a solid foundation for integrating databases into your JavaScript applications. Explore further and dive deeper into the world of database-driven web development to harness the full power of your data.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (1)

Collapse
 
nhathuoc115com profile image
Nhà thuốc 115 thuoc115.com

Thank you

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️