Node.js theorytheory 0/50 · 0%
Data · medium

29. Working with databases

Connection pools, parameterized queries and async access patterns.

Node talks to databases through driver libraries (`pg` for Postgres, `mysql2`, or ORMs like Prisma) that expose async, Promise-based query APIs backed by a connection pool — reusing a small set of open connections instead of opening one per request.

js
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function getBalance(address) {
  const { rows } = await pool.query(
    "SELECT balance FROM accounts WHERE address = $1",
    [address], // parameterized — never string-concatenate user input into SQL
  );
  return rows[0]?.balance ?? "0";
}

Always use parameterized queries (placeholders like `$1` or `?`) instead of building SQL with template literals — string-concatenating user input directly into a query is the classic SQL injection vulnerability.

Check your understanding

  1. 1. Why use a connection pool instead of opening a new database connection per request?

  2. 2. What vulnerability does string-concatenating user input into SQL create?

  3. 3. What should be used instead of concatenating values into a query string?