The mysql2 package connects Node.js to MySQL or MariaDB and supports promises.
Install
npm install mysql2
Use a connection pool
A pool keeps several connections open and reuses them — much faster than connecting for every request. Create it once and share it.
Query with placeholders
const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [id]);
?placeholders send values separately from the SQL, which prevents SQL injection- Never build SQL with string templates like
`... WHERE id = ${id}` execute()returns[rows, fields]- For INSERT,
result.insertIdgives the new id; for UPDATE/DELETE,result.affectedRows
Transactions
When several queries must all succeed (for example, place an order and reduce stock), get a connection, beginTransaction(), then commit() — or rollback() on error — and finally release().
For bigger projects, an ORM or query builder such as Prisma, Sequelize, Drizzle or Knex can help.
Example
// db.js
import mysql from 'mysql2/promise';
export const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
});
// app.js
import express from 'express';
import { pool } from './db.js';
const app = express();
app.use(express.json());
app.get('/api/students/:id', async (req, res) => {
const [rows] = await pool.execute('SELECT id, name, course FROM students WHERE id = ?', [req.params.id]);
rows.length ? res.json(rows[0]) : res.status(404).json({ error: 'Student not found' });
});
app.post('/api/students', async (req, res) => {
const { name, course } = req.body;
const [result] = await pool.execute('INSERT INTO students (name, course) VALUES (?, ?)', [name, course]);
res.status(201).json({ id: result.insertId, name, course });
});
app.listen(3000);
GET /api/students/1 returns that student as JSON, and POST /api/students inserts a row and returns its new id. Placeholders keep both queries safe from SQL injection.