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.
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);[{ id: 1, name: 'Ada' }]The $1 placeholder safely inserts the parameter, avoiding SQL injection.
await pool.query('INSERT INTO users (name) VALUES ($1)', ['Grace']);INSERT 0 1Parameterized 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.
