Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

Connecting PostgreSQL with Node.js in the PERN Stack

Introduction

In the previous article, we successfully set up our PERN stack development environment by installing:

  • Node.js

  • PostgreSQL

  • React

  • Express.js

Now it is time to move into real backend development by connecting PostgreSQL with Node.js.

This is one of the most important steps in the PERN stack because databases are responsible for storing and managing application data.

In this article, we will learn:

  • How PostgreSQL works with Node.js

  • Creating a database

  • Creating tables

  • Connecting Express server with PostgreSQL

  • Writing SQL queries

  • Performing basic CRUD operations


Understanding Database Connectivity

In the PERN stack:

  • React handles frontend UI

  • Express and Node.js handle backend logic

  • PostgreSQL stores data permanently

The backend communicates with PostgreSQL using the pg package.

Flow of Data

React → Express API → PostgreSQL Database

Whenever a user submits data:

  1. React sends request

  2. Express receives request

  3. Node.js processes logic

  4. PostgreSQL stores or retrieves data

  5. Response returns to frontend


Step 1: Install PostgreSQL Driver

Inside your server folder install the PostgreSQL package:

npm install pg

The pg package allows Node.js to communicate with PostgreSQL.


Step 2: Create a PostgreSQL Database

Open:

  • pgAdmin
    or

  • PostgreSQL terminal (psql)

Create a database named:

CREATE DATABASE pern_app;

Step 3: Create a Table

Now connect to the database and create a table.

Example: Student table

CREATE TABLE students(
    student_id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    course VARCHAR(50),
    age INTEGER
);

Understanding Table Structure

ColumnDescription
student_idUnique ID
nameStudent name
courseCourse name
ageStudent age

Step 4: Create Database Connection File

Inside the server folder create:

db.js

Add the following code:

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

const pool = new Pool({
    user: 'postgres',
    password: 'your_password',
    host: 'localhost',
    port: 5432,
    database: 'pern_app'
});

module.exports = pool;

Understanding the Connection Code

Pool

The Pool object manages multiple database connections efficiently.


Connection Parameters

ParameterPurpose
userPostgreSQL username
passwordPostgreSQL password
hostDatabase server
portPostgreSQL port
databaseDatabase name

Step 5: Setup Express Server

Open your index.js file.

Add this code:

const express = require('express');
const cors = require('cors');
const pool = require('./db');

const app = express();

app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
    res.send('Database Connected Successfully');
});

app.listen(5000, () => {
    console.log('Server running on port 5000');
});

Step 6: Test Database Connection

Now run the server:

npx nodemon index.js

If everything is correct, your server will run without errors.


Step 7: Insert Data into Database

Now let’s create our first API to insert student data.

Add this route inside index.js:

app.post('/students', async (req, res) => {
    try {
        const { name, course, age } = req.body;

        const newStudent = await pool.query(
            'INSERT INTO students(name, course, age) VALUES($1, $2, $3) RETURNING *',
            [name, course, age]
        );

        res.json(newStudent.rows[0]);

    } catch (err) {
        console.error(err.message);
    }
});

Understanding the Insert Query

INSERT INTO students(name, course, age)
VALUES($1, $2, $3)
RETURNING *
  • $1, $2, $3 are placeholders

  • Prevents SQL injection attacks

  • RETURNING * returns inserted data


Step 8: Test API Using Thunder Client or Postman

Request Type

POST

URL

http://localhost:5000/students

JSON Body

{
    "name": "Shivam",
    "course": "BCA",
    "age": 20
}

Step 9: Fetch Data from Database

Now create API to get all students.

app.get('/students', async (req, res) => {
    try {

        const allStudents = await pool.query(
            'SELECT * FROM students'
        );

        res.json(allStudents.rows);

    } catch (err) {
        console.error(err.message);
    }
});

Step 10: Get Single Student

app.get('/students/:id', async (req, res) => {
    try {

        const { id } = req.params;

        const student = await pool.query(
            'SELECT * FROM students WHERE student_id = $1',
            [id]
        );

        res.json(student.rows[0]);

    } catch (err) {
        console.error(err.message);
    }
});

Step 11: Update Student Data

app.put('/students/:id', async (req, res) => {
    try {

        const { id } = req.params;
        const { name, course, age } = req.body;

        await pool.query(
            'UPDATE students SET name=$1, course=$2, age=$3 WHERE student_id=$4',
            [name, course, age, id]
        );

        res.json('Student Updated');

    } catch (err) {
        console.error(err.message);
    }
});

Step 12: Delete Student Data

app.delete('/students/:id', async (req, res) => {
    try {

        const { id } = req.params;

        await pool.query(
            'DELETE FROM students WHERE student_id = $1',
            [id]
        );

        res.json('Student Deleted');

    } catch (err) {
        console.error(err.message);
    }
});

Understanding CRUD Operations

CRUD stands for:

OperationMeaning
CreateInsert data
ReadFetch data
UpdateModify data
DeleteRemove data

CRUD operations form the foundation of almost every web application.


Why Async/Await is Used

Database operations take time.

Using:

async/await

helps Node.js handle operations efficiently without freezing the server.


Common Errors and Solutions

1. Password Authentication Failed

Check:

  • PostgreSQL password

  • Username

  • Database name


2. Database Does Not Exist

Run:

CREATE DATABASE pern_app;

3. Table Does Not Exist

Check spelling and create table again.


4. Port Already in Use

Change port inside:

app.listen(5000)

Real-World Uses of Database APIs

These APIs are used in:

  • Student management systems

  • Test series platforms

  • E-commerce websites

  • Banking systems

  • Hospital management software


Best Practices

Use Environment Variables

Instead of writing passwords directly:

password: 'your_password'

Use .env files for security.


Validate User Input

Always check:

  • Empty fields

  • Invalid values

  • SQL injection prevention


Organize Project Structure

Create separate folders for:

  • Routes

  • Controllers

  • Database

  • Middleware

This makes large projects manageable.


Conclusion

You have now successfully connected PostgreSQL with Node.js and created your first backend APIs using the PERN stack.

You learned:

  • Database connection

  • SQL queries

  • CRUD operations

  • API creation

  • Express integration

This is the foundation of backend development in modern web applications.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...