Node.js / Node.js Database Integration

Integrating MySQL and PostgreSQL with Node.js

In this tutorial, we will explore how to integrate MySQL and PostgreSQL with Node.js. These powerful relational databases can be harnessed to create more dynamic and data-intensiv…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers integrating Node.js with databases such as MongoDB, MySQL, and PostgreSQL.

Integrating MySQL and PostgreSQL with Node.js

1. Introduction

In this tutorial, our goal is to understand how to integrate MySQL and PostgreSQL with Node.js. These robust relational databases can significantly enhance the dynamism and data-centricity of your web applications.

By the end of this guide, you will be able to set up a connection to MySQL and PostgreSQL databases using Node.js and be able to perform CRUD operations.

Prerequisites:

  • Basic understanding of JavaScript
  • Node.js and NPM installed on your machine
  • MySQL and PostgreSQL installed on your machine

2. Step-by-Step Guide

First, we need to install the necessary modules. For MySQL we will use the mysql module, and for PostgreSQL, we will use the pg module.

npm install mysql pg

Connecting to MySQL:

const mysql = require('mysql');

// Create connection
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'nodemysql'
});

// Connect
db.connect((err) => {
  if(err) throw err;
  console.log('MySQL Connected...');
});

Connecting to PostgreSQL:

const { Client } = require('pg');

// Create client
const client = new Client({
  host: 'localhost',
  user: 'postgres',
  password: 'password',
  database: 'node_postgres',
});

// Connect
client.connect(err => {
  if (err) {
    console.error('connection error', err.stack)
  } else {
    console.log('PostgreSQL Connected...')
  }
});

3. Code Examples

MySQL CRUD Operations:

// Create database
let sql = 'CREATE DATABASE nodemysql';
db.query(sql, (err, result) => {
    if(err) throw err;
    console.log(result);
    console.log('Database created...');
});

// Insert post
let post = {title:'Post One', body:'This is post number one'};
let sql = 'INSERT INTO posts SET ?';
let query = db.query(sql, post, (err, result) => {
    if(err) throw err;
    console.log(result);
    console.log('Post added...');
});

// Select posts
let sql = 'SELECT * FROM posts';
let query = db.query(sql, (err, results) => {
    if(err) throw err;
    console.log(results);
    console.log('Posts fetched...');
});

// Delete post
let sql = `DELETE FROM posts WHERE title = 'Post One'`;
let query = db.query(sql, (err, result) => {
    if(err) throw err;
    console.log(result);
    console.log('Post deleted...');
});

PostgreSQL CRUD Operations:

// Create table
client.query('CREATE TABLE posts(id SERIAL PRIMARY KEY, title VARCHAR(50), body VARCHAR(255))', (err, res) => {
  if(err) throw err;
  console.log('Table created...');
});

// Insert post
let postText = 'INSERT INTO posts(title, body) VALUES($1, $2) RETURNING *';
let values = ['Post One', 'This is post number one'];
client.query(postText, values, (err, res) => {
  if(err) throw err;
  console.log('Post added...');
});

// Select posts
client.query('SELECT * FROM posts', (err, res) => {
  if(err) throw err;
  console.log(res.rows);
});

// Delete post
let deleteText = 'DELETE FROM posts WHERE title = $1';
let deleteValue = ['Post One'];
client.query(deleteText, deleteValue, (err, res) => {
  if(err) throw err;
  console.log('Post deleted...');
});

4. Summary

In this tutorial, we learned how to integrate MySQL and PostgreSQL with Node.js, how to connect to the databases, and perform basic CRUD operations.

The next step would be to understand how to handle errors and exceptions while working with these databases.

Additional resources:
- MySQL NPM
- Node Postgres

5. Practice Exercises

  1. Create a new PostgreSQL database and connect to it using Node.js.
  2. Create a new table in the PostgreSQL database and insert 5 different posts into it.
  3. Create a new MySQL database and perform the same operations as in exercises 1 and 2.

Remember to practice handling errors and exceptions while working with these databases.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help