codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

33 / 63 topics
30Database Integration31MongoDB with Node.js32Mongoose ORM33SQL Databases with Node.js34Sequelize ORM
Tutorials/Node.js/SQL Databases with Node.js
🟢Node.js

SQL Databases with Node.js

Updated 2026-05-15
10 min read

SQL Databases with Node.js

Introduction

In the world of web development, data persistence is a crucial aspect. Storing and retrieving data efficiently ensures that applications can handle user interactions seamlessly. Node.js, being a versatile JavaScript runtime environment, provides several ways to interact with databases. In this tutorial, we will explore how to connect to SQL databases like MySQL and PostgreSQL using Node.js.

Concept

SQL (Structured Query Language) is a standard language for managing relational databases. It allows you to create, read, update, and delete data in a database. Node.js can be used to interact with these databases through various libraries that provide APIs for executing SQL queries.

Key Concepts

  • Database Connection: Establishing a connection to the database.
  • Query Execution: Running SQL queries to perform CRUD operations.
  • Error Handling: Managing errors that may occur during database interactions.

Examples

Let's dive into practical examples of connecting to MySQL and PostgreSQL databases using Node.js.

Connecting to MySQL

To connect to a MySQL database, you can use the mysql package. First, install the package:

Terminal

Next, create a file named postgresConnection.js and add the following code:

JavaScript
1const { Client } = require('pg');
2
3// Create a new client
4const client = new Client({
5user: 'your_username',
6host: 'localhost',
7database: 'your_database',
8password: 'your_password',
9port: 5432,
10});
11
12// Connect to the database
13client.connect()
14.then(() => console.log('Connected to PostgreSQL database!'))
15.catch(err => console.error('Error connecting to PostgreSQL:', err));

Executing Queries

Once connected, you can execute SQL queries. Here’s how you can perform a simple query in both MySQL and PostgreSQL.

MySQL Query Example

Add the following code to mysqlConnection.js:

JavaScript
1// Execute a query
2connection.query('SELECT 1 + 1 AS solution', (error, results, fields) => {
3if (error) throw error;
4console.log('The solution is: ', results[0].solution);
5});

PostgreSQL Query Example

Add the following code to postgresConnection.js:

JavaScript
1// Execute a query
2client.query('SELECT $1::text as message', ['Hello world!'])
3.then(res => console.log(res.rows[0].message))
4.catch(err => console.error('Error executing query:', err));

Error Handling

It's important to handle errors properly to ensure your application can gracefully handle issues that arise during database interactions.

MySQL Error Handling

In the MySQL example, we already have a basic error handling mechanism in place:

JavaScript
1connection.connect((err) => {
2if (err) {
3 console.error('Error connecting to MySQL:', err);
4 return;
5}
6console.log('Connected to MySQL database!');
7});

PostgreSQL Error Handling

In the PostgreSQL example, we handle errors using .catch():

JavaScript
1client.connect()
2.then(() => console.log('Connected to PostgreSQL database!'))
3.catch(err => console.error('Error connecting to PostgreSQL:', err));

What's Next?

Now that you have a basic understanding of how to connect and interact with SQL databases using Node.js, the next step is to explore an ORM (Object-Relational Mapping) tool like Sequelize. Sequelize provides a more abstracted way to interact with databases, making it easier to manage complex data models.

Stay tuned for more tutorials on advanced database interactions with Node.js!

Info

Remember to replace 'your_username', 'your_password', and 'your_database' with your actual database credentials.

PreviousMongoose ORMNext Sequelize ORM

Recommended Gear

Mongoose ORMSequelize ORM