Bird
Raised Fist0
Node.jsframework~10 mins

PostgreSQL connection with pg in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - PostgreSQL connection with pg
Import pg module
↓
Create Client with config
↓
Call client.connect()
↓
Connection established?
No→Error Handling
Yes↓
Use client to query database
↓
Process query results
↓
Close connection with client.end()
This flow shows how to import the pg module, create a client, connect to PostgreSQL, run queries, and close the connection.
Execution Sample
Node.js
import { Client } from 'pg';

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

await client.connect();
This code imports pg, creates a client with connection info, and connects to the PostgreSQL server.
Execution Table
StepActionEvaluationResult
1Import pg ClientModule 'pg' importedClient class ready
2Create Client instanceClient config setClient object created
3Call client.connect()Attempt connection to DBConnection successful
4Run query client.query('SELECT 1')Send query to DBQuery result received
5Process query resultExtract rowsRows available
6Call client.end()Close connectionConnection closed
💡 Connection closed after query and processing
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6
clientundefinedClient object with configConnected client instanceClosed client instance
Key Moments - 2 Insights
Why do we need to call client.connect() before querying?
Because the client must establish a connection to the database server first, as shown in step 3 of the execution_table. Without connecting, queries cannot be sent.
What happens if client.end() is not called?
The connection stays open, which can cause resource leaks. Step 6 shows closing the connection to free resources.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the client state after step 3?
AConnection successful and client ready
BConnection failed
CClient object created but not connected
DConnection closed
💡 Hint
Refer to row 3 in execution_table where client.connect() is called and connection is successful
At which step is the query sent to the database?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Action' column in execution_table row 4 for query sending
If client.end() is skipped, what changes in variable_tracker after step 6?
Aclient becomes undefined
Bclient remains connected
Cclient is closed anyway
Dclient throws error
💡 Hint
Check variable_tracker for client state after step 6 and consider what happens if end() is not called
Concept Snapshot
PostgreSQL connection with pg:
1. Import Client from 'pg'.
2. Create Client with config (user, host, db, password, port).
3. Call client.connect() to open connection.
4. Use client.query() to run SQL.
5. Process results.
6. Call client.end() to close connection.
Full Transcript
This lesson shows how to connect to a PostgreSQL database using the 'pg' module in Node.js. First, we import the Client class from 'pg'. Then, we create a new Client instance with connection details like user, host, database, password, and port. Next, we call client.connect() to establish the connection. After connecting, we can run queries using client.query(). Once done, we process the results and finally call client.end() to close the connection and free resources. Each step is important to ensure proper communication with the database and resource management.

Practice

(1/5)
1. What is the main purpose of the pg library in Node.js?
easy
A. To connect and interact with PostgreSQL databases
B. To create web servers
C. To manage file uploads
D. To style web pages

Solution

  1. Step 1: Understand the role of pg

    The pg library is designed specifically to connect Node.js applications to PostgreSQL databases.
  2. Step 2: Compare with other options

    Creating web servers, managing file uploads, and styling pages are unrelated to database connections and are handled by other libraries.
  3. Final Answer:

    To connect and interact with PostgreSQL databases -> Option A
  4. Quick Check:

    pg = PostgreSQL connection [OK]
Hint: Remember pg is for PostgreSQL database connection [OK]
Common Mistakes:
  • Confusing pg with web server libraries
  • Thinking pg handles frontend styling
  • Assuming pg manages file uploads
2. Which of the following is the correct way to create a new Client instance from the pg library?
easy
A. const client = pg.connect('postgresql://user:pass@localhost/db');
B. const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' });
C. const client = new Client.connect('postgresql://user:pass@localhost/db');
D. const client = pg.new Client('postgresql://user:pass@localhost/db');

Solution

  1. Step 1: Recall the correct Client creation syntax

    The pg library requires creating a new Client instance using new pg.Client() with a config object.
  2. Step 2: Check each option's syntax

    const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' }); correctly uses new pg.Client({ connectionString: ... }). Options B, C, and D use invalid syntax or methods that do not exist.
  3. Final Answer:

    const client = new pg.Client({ connectionString: 'postgresql://user:pass@localhost/db' }); -> Option B
  4. Quick Check:

    Use new pg.Client with config object [OK]
Hint: Use 'new pg.Client' with config object for connection [OK]
Common Mistakes:
  • Calling pg.connect directly without new Client
  • Using incorrect method names like Client.connect
  • Missing the 'new' keyword when creating Client
3. What will the following code output if the query succeeds?
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });

async function run() {
  await client.connect();
  const res = await client.query('SELECT 1 AS number');
  console.log(res.rows[0].number);
  await client.end();
}

run();
medium
A. 1
B. [{ number: 1 }]
C. undefined
D. Error: query failed

Solution

  1. Step 1: Understand the query and result structure

    The query SELECT 1 AS number returns one row with a column named 'number' having value 1.
  2. Step 2: Check how the result is accessed

    The code logs res.rows[0].number, which accesses the first row's 'number' field, so it prints 1.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    res.rows[0].number = 1 [OK]
Hint: Access query result via res.rows[0].columnName [OK]
Common Mistakes:
  • Logging res.rows instead of a specific field
  • Expecting the whole array instead of one value
  • Not awaiting client.connect() before query
4. Identify the error in this code snippet that uses pg to connect to PostgreSQL:
const { Client } = require('pg');
const client = new Client({ connectionString: 'postgresql://user:pass@localhost/db' });

client.connect();
const res = await client.query('SELECT NOW()');
console.log(res.rows[0]);
client.end();
medium
A. client.end() should be called before query
B. client.query() should not be awaited
C. No error, code is correct
D. Missing await before client.connect()

Solution

  1. Step 1: Check async usage for connect()

    The client.connect() method returns a promise and must be awaited to ensure connection before querying.
  2. Step 2: Verify other async calls

    The await before client.query() is correct. Calling client.end() after query is also correct.
  3. Final Answer:

    Missing await before client.connect() -> Option D
  4. Quick Check:

    Always await client.connect() before queries [OK]
Hint: Always await client.connect() before querying [OK]
Common Mistakes:
  • Not awaiting client.connect() causing race conditions
  • Awaiting client.query() is correct, so skipping it is wrong
  • Calling client.end() too early before query finishes
5. You want to write a Node.js function using pg that connects to PostgreSQL, runs a query, and always closes the connection even if an error occurs. Which pattern is best?
hard
A. Call connect, query, and end sequentially without error handling
B. Only call client.end() if query succeeds, skip on error
C. Use try-catch-finally: connect in try, query in try, close in finally
D. Use callbacks instead of async/await for better error handling

Solution

  1. Step 1: Understand error-safe connection handling

    To ensure the connection closes even if an error happens, use a try-catch-finally block where client.end() is called in the finally block.
  2. Step 2: Evaluate options for best practice

    Use try-catch-finally: connect in try, query in try, close in finally correctly uses try-catch-finally. Call connect, query, and end sequentially without error handling lacks error handling. Only call client.end() if query succeeds, skip on error risks leaving connection open on errors. Use callbacks instead of async/await for better error handling is outdated compared to async/await.
  3. Final Answer:

    Use try-catch-finally: connect in try, query in try, close in finally -> Option C
  4. Quick Check:

    try-catch-finally ensures connection closes [OK]
Hint: Use try-catch-finally to always close connection [OK]
Common Mistakes:
  • Not closing connection on errors
  • Ignoring async/await for error handling
  • Closing connection only on success
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard