A simple example to access a PostgreSQL database in Node.js

CK CK 3788 
Created at
Updated at  
1,101 0 0

To access a PostgreSQL database from a Node.js application, you can use the pg library, which is a popular PostgreSQL client for Node.js.

 

Here’s a simple example demonstrating how to connect to a PostgreSQL database, execute a query, and retrieve results using the pg library.

 

Step 1: Install the pg Library

First, you need to install the pg library:

npm install pg

 

Step 2: Write Node.js Code to Access PostgreSQL

Create a file named postgres-example.js and add the following code:

File: postgres-example.js

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

// Define your PostgreSQL database connection details
const client = new Client({
  user: 'your-username',
  host: 'localhost',
  database: 'your-database',
  password: 'your-password',
  port: 5432, // Default PostgreSQL port
});

// Connect to the PostgreSQL database
client.connect()
  .then(() => {
    console.log('Connected to PostgreSQL database');
    
    // Define a SQL query
    const query = 'SELECT NOW() AS current_time';
    
    // Execute the query
    return client.query(query);
  })
  .then((res) => {
    // Print the results
    console.log('Query Results:', res.rows);
  })
  .catch((err) => {
    console.error('Error:', err);
  })
  .finally(() => {
    // Close the database connection
    client.end();
  });

 

Explanation

  1. Import pg Library: Import the Client class from the pg library.
  2. Configure Database Connection: Create a new Client instance with the connection details, including the user, host, database, password, and port. Adjust these values based on your PostgreSQL setup.
  3. Connect to Database: Use client.connect() to establish a connection to the PostgreSQL database.
  4. Execute a Query: Define and execute a SQL query using client.query(). In this example, we’re retrieving the current time from the database.
  5. Handle Results: Log the query results. The results are returned as an array of objects in res.rows.
  6. Error Handling: Catch and log any errors that occur during the connection or query execution.
  7. Close Connection: Ensure the database connection is closed with client.end() after completing the operations.

 

Running the Script

Execute the script with Node.js:

node postgres-example.js

Notes

  • Replace Placeholder Values: Make sure to replace 'your-username', 'your-database', and 'your-password' with your actual PostgreSQL credentials.
  • Database Schema: Adjust the SQL query to match your database schema and requirements.
  • Environment Variables: For security, consider using environment variables or a configuration file to store your database credentials instead of hardcoding them into your script.

This example provides a basic setup for connecting to and querying a PostgreSQL database in a Node.js application.

Tags PSQL PostgreSQL Facebook X
Comments 0
Similar posts
  1. When you Postgresql Module is not able to open connection : Doubt your libpq version
    480
  1. Get client IP address and user agent in Node.js
    1,531
  2. forEach method in JavaScript when working with arrays
    667
  3. CRC32B function code in Javascript
    1,843
  4. Node.js-based Web Server supporting multiple path
    602
  5. A simple Javascript class example with static method for Node.js
    661
  6. Setting a Common Path for require() in Node.js
    1,007
  7. Import all JS files in a specific folder for Node.js programming
    1,732
  8. Node.js code example to access Google BigQuery
    1,183
  9. Investigation on package.js for Node.js source code
    824
  10. Using MySQL in Node.js
    484
  11. A Node.js script that checks if a module is installed before requiring it
    774
  12. Worker Threads and Mutual Exclusion in Node.js
    466
  13. Using a module in the external class itself without creating an instance in Node.js
    350
  14. Node.js external modules
    434
  15. Multi-threaded Web Server based in Node.js
    866
  16. A basic HTTP server based in Node.js
    544
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,197
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    98
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    268
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    354
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    229
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    203
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233