DEV Community

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

Posted on

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.

Top comments (1)

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

Thank you