</>
Skip to content
Node.js lessons (41/44)

Node.js — PostgreSQL

Installation

npm install pg

Connection

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

const client = new Client({
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'password',
    database: 'mydb'
});

await client.connect();

Pool

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

const pool = new Pool({
    host: 'localhost',
    user: 'postgres',
    password: 'password',
    database: 'mydb',
    max: 20
});

const result = await pool.query('SELECT * FROM users');

Querying

// Simple query
const result = await pool.query('SELECT * FROM users');

// Parameterized query
const result = await pool.query(
    'SELECT * FROM users WHERE id = $1',
    [userId]
);

// Insert
await pool.query(
    'INSERT INTO users (name, email) VALUES ($1, $2)',
    ['John', 'john@example.com']
);

CRUD Operations

// Read
const { rows } = await pool.query('SELECT * FROM users');

// Create
await pool.query(
    'INSERT INTO users (name, email) VALUES ($1, $2)',
    [name, email]
);

// Update
await pool.query(
    'UPDATE users SET name = $1 WHERE id = $2',
    [name, id]
);

// Delete
await pool.query('DELETE FROM users WHERE id = $1', [id]);

Mini Practice

  1. Set up PostgreSQL connection
  2. Use connection pooling
  3. Perform parameterized queries
  4. Implement CRUD operations

Up Next

Continue with Testing — writing tests in Node.js.

Related Topics

Frequently Asked Questions about PostgreSQL

What is PostgreSQL in Node.js?

PostgreSQL is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn PostgreSQL?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn PostgreSQL.

Why is PostgreSQL important in Node.js?

PostgreSQL is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.