Languages
[Edit]
EN

Node.js - how to connect with PostgreSQL

0 points
Created by:
Brett4
435

In this article, we would like to show you how to use PostgreSQL in Node.js.

Step 1 - Install the node-postgres module in your Node project. 

npm install pg

Step 2 - Import the pg module by using require and create a connection with the PostgreSQL database. 

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

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

const execute = async () => {
    try {
        await client.connect();             // gets connection with database
        console.log('database connected');  // sends queries
    } catch (error) {
        console.log(error.stack);
    } finally {
        await client.end();                 // closes connection 
    }
};

execute();

That's it, you've been connected and from now on you can query your database.

Practical example with SELECT query: 

  • with async/await
const { Client } = require('pg');

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

const execute = async () => {
    try {
        await client.connect();                                     // gets connection
        const response = await client.query('SELECT * FROM users'); // sends queries
        console.log(response.rows);
    } catch (error) {
        console.log(error.stack);
    } finally {
        await client.end();                                         // closes connection 
    }
};

execute();
  • with promises
const { Client } = require('pg');

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

client
    .connect()                                                         // gets connection
    .then(() => console.log('database connected'))
    .catch((error) => console.error('connection error', error.stack))
    .then(() => client.query('SELECT * FROM users'))                   // sends queries
    .then((result) => console.log(JSON.stringify(result.rows, null, 4)))
    .catch((error) => console.error('query error', error.stack))
    .finally(() => client.end());                                      // closes connection 

References: 

  1. pg package - npm

Alternative titles

  1. Node.js - how to install PostgreSQL
  2. How to use PostgreSQL in Node
  3. Node.js - install PostgreSQL Driver
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join