agyanadda@gmail.com

Node.js with MySQL

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 21 of 30

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.insertId gives 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

Example — Database module and a query JavaScript
// 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does a ? in a mysql2 query do?

Exercise 2 True / False

A connection pool reuses database connections across requests.

Exercise 3 Fill in the Blank

After an INSERT, the new id is in result.___

Frequently Asked Questions

That error comes from the old mysql package with newer MySQL servers. Use the mysql2 package instead, which supports the modern authentication method.