0
0
Node.jsframework~5 mins

PostgreSQL connection with pg in Node.js

Choose your learning style9 modes available
Introduction

We use the pg library to connect Node.js apps to PostgreSQL databases. It helps us send queries and get data easily.

You want to save user data from a web form into a PostgreSQL database.
You need to read data from PostgreSQL to show on a website.
You want to update or delete records in PostgreSQL from your Node.js app.
You are building a backend API that talks to PostgreSQL.
You want to run SQL commands from your JavaScript code.
Syntax
Node.js
import { Client } from 'pg';

async function main() {
  const client = new Client({
    user: 'yourUsername',
    host: 'localhost',
    database: 'yourDatabase',
    password: 'yourPassword',
    port: 5432
  });

  await client.connect();

  // Run queries here

  await client.end();
}

main();

Replace connection details with your own database info.

Always call connect() before running queries and end() when done.

Examples
Using a connection string instead of separate options.
Node.js
import { Client } from 'pg';

async function main() {
  const client = new Client({
    connectionString: 'postgresql://user:password@localhost:5432/mydb'
  });

  await client.connect();

  // Run queries here

  await client.end();
}

main();
Run a simple query to get the current time from PostgreSQL.
Node.js
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
Sample Program

This program connects to PostgreSQL, runs a simple query that returns a message, prints it, and then closes the connection.

Node.js
import { Client } from 'pg';

async function run() {
  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'testdb',
    password: 'mypassword',
    port: 5432
  });

  try {
    await client.connect();
    const res = await client.query('SELECT $1::text as message', ['Hello, pg!']);
    console.log(res.rows[0].message);
  } catch (err) {
    console.error('Error connecting or querying', err);
  } finally {
    await client.end();
  }
}

run();
OutputSuccess
Important Notes

Make sure PostgreSQL server is running and accessible.

Never hardcode passwords in real apps; use environment variables.

Use try/catch to handle errors when connecting or querying.

Summary

The pg library lets Node.js talk to PostgreSQL easily.

Set up a Client with your database info, connect, query, then close.

Always handle errors and close connections to keep your app stable.