Databases & Data Access
Node.js MySQL and PostgreSQL
Node connects to relational databases through driver packages — mysql2 for MySQL and pg for PostgreSQL. Both support connection pooling and parameterised queries, which are essential for performance and safety.
What is MySQL and PostgreSQL in Node.js?
Node connects to relational databases through driver packages — mysql2 for MySQL and pg for PostgreSQL. Both support connection pooling and parameterised queries, which are essential for performance and safety.
MySQL and PostgreSQL example
JavaScript
import mysql from 'mysql2/promise';
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: 'jobs',
connectionLimit: 10,
});
// parameterised — the ONLY safe way to include user input
const [rows] = await pool.execute(
'SELECT id, title FROM jobs WHERE city = ? AND status = ? LIMIT ?',
[city, 'active', 20]
);
// PostgreSQL uses $1, $2 placeholders
const { rows } = await pgPool.query(
'SELECT id, title FROM jobs WHERE city = $1 LIMIT $2',
[city, 20]
);Key points to remember
- Create one pool at startup and reuse it — never one connection per request.
- Always parameterise; string concatenation is SQL injection.
- Use a transaction when several writes must succeed or fail together.
- Prisma, Drizzle, Knex and Sequelize add query building and migrations on top.
Common mistakes with MySQL and PostgreSQL
- Building SQL with template literals containing user input.
- Opening a connection per request and exhausting the database’s connection limit.
- Forgetting to release a connection taken from the pool for a transaction.
Node.js MySQL and PostgreSQL— Interview Questions & FAQs
How do I prevent SQL injection in Node.js?+
Use parameterised queries — pass values as an array with ? or $1 placeholders and never concatenate user input into the SQL string. Every mainstream driver and ORM supports this.
