CodeBlanks Logo Icon CodeBlanks

pg module

Learn PostgreSQL connection with the pg module.

What is the pg module?

pg is the most popular PostgreSQL client module for Node.js. It offers both a single connection (Client) and a connection pool (Pool). Install: npm install pg.

PostgreSQL is a powerful open-source relational database. The pg module runs SQL queries as parameterized statements; this is the basic protection against SQL injection. The Pool reuses connections to boost performance; it does not open a new connection per request.

Client and Pool

pg offers two connection models. A Client is a single connection; it is handy for short scripts. A Pool is a connection pool; it is preferred in web servers.

The Pool opens several connections up front and distributes them to requests. You create it with const pool = new Pool({ connectionString: "..." }). Query: pool.query("SELECT * FROM users"). Each query borrows a connection from the pool and returns it when done. This reduces the cost of opening and closing connections.

Practice Log the type of Pool

Import the Pool class from pg. Log typeof Pool.

Starter code

index.js
// import the module, get the Pool class

// log its type

Sample solution

index.js
const { Pool } = require("pg");
console.log(typeof Pool);

Expected output

function

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which database does the pg module connect to?

  • MongoDB
  • MySQL
  • PostgreSQL Correct answer
  • SQLite

Explanation: The pg module connects to PostgreSQL.

2 Complete the module name

Question
const { Pool } = require("____")
Answer
const { Pool } = require("pg")

Explanation: The pg module loads as 'pg'.

3 Match each piece to its role

Term Meaning
pg PostgreSQL client
Pool Connection pool
Client Single connection
pool.query Runs a query

All lessons in Advanced