Tags:

To connect a PostgreSQL database with Node.js, you can use the pg package, which is a popular client for PostgreSQL in Node.js.


Steps to Connect PostgreSQL to Node.js:

  1. Install the pg Package
    Use npm to install the pg module. npm install pg

  1. Set Up Connection to PostgreSQL
    Use the Client class to establish a connection.

Example Code:

// Step 1: Import the pg module
const { Client } = require('pg');

// Step 2: Create a new PostgreSQL client
const client = new Client({
  host: 'localhost',          // Database host
  user: 'your_username',      // Database username
  password: 'your_password',  // Database password
  database: 'your_db_name',   // Database name
  port: 5432,                 // Default PostgreSQL port
});

// Step 3: Connect to the database
client.connect()
  .then(() => console.log('Connected to PostgreSQL'))
  .catch(err => console.error('Connection error', err.stack));

// Step 4: Query the database
client.query('SELECT * FROM your_table_name', (err, res) => {
  if (err) {
    console.error('Error executing query', err.stack);
  } else {
    console.log('Query results:', res.rows);
  }

  // Step 5: Close the connection
  client.end();
});

Key Points:

  1. Connection Parameters:
    • host: The PostgreSQL server (usually localhost for local development).
    • user: Your PostgreSQL username.
    • password: Your PostgreSQL password.
    • database: The name of the database.
    • port: Default PostgreSQL port is 5432.
  2. Connecting:
    • client.connect() establishes the connection.
    • Handle success or errors using .then() or .catch().
  3. Querying:
    • client.query() executes SQL queries. Replace 'SELECT * FROM your_table_name' with your desired query.
    • Results are returned in res.rows, which contains the fetched data.
  4. Closing Connection:
    • Use client.end() to close the database connection.

Output Example:

If the table contains data, the output in the terminal would look like:

Connected to PostgreSQL
Query results: [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]

Alternative: Use Pool for Connection Pooling

If your app requires multiple queries and connections, use Pool instead of Client for better performance.

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

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

pool.query('SELECT * FROM your_table_name', (err, res) => {
  if (err) {
    console.error('Error executing query', err.stack);
  } else {
    console.log('Query results:', res.rows);
  }
  pool.end();
});

By following these steps, you can successfully connect and interact with a PostgreSQL database in a Node.js application.