Node.js ยท Chapter 26 of 43

SQL Basics with Node.js

Node.js can also work with relational (SQL) databases like PostgreSQL and MySQL using driver packages such as `pg` or `mysql2`.

SQL databases enforce a fixed schema and use structured query language for reading and writing data, offering strong consistency guarantees.

Connecting to a database

Driver libraries provide a connection pool or client object used to run queries against the database server.

Running queries

Use parameterized queries (with placeholders) to safely insert user data and prevent SQL injection.

Example 1 (javascript)
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const result = await pool.query('SELECT * FROM users WHERE id = $1', [1]);
console.log(result.rows);
Output
[{ id: 1, name: 'Ada' }]

The $1 placeholder safely inserts the parameter, avoiding SQL injection.

Example 2 (javascript)
await pool.query('INSERT INTO users (name) VALUES ($1)', ['Grace']);
Output
INSERT 0 1

Parameterized inserts keep queries safe even with untrusted input.

Key points

  • Node.js can connect to SQL databases via drivers like pg or mysql2.
  • SQL databases enforce a fixed schema.
  • Always use parameterized queries, never string concatenation.
  • Connection pools manage multiple simultaneous connections efficiently.
๐Ÿ’ก Note: ORMs like Prisma or Sequelize can simplify SQL access even further.

๐Ÿ“ Quick Quiz

1. Which npm package is commonly used for PostgreSQL?

2. Why use parameterized queries?

3. What manages multiple simultaneous DB connections efficiently?