Skip to main content
Almost every real API persists data to a database. This page teaches you how to connect a Node.js Express application to a MySQL database using the mysql2 library, create a connection, and run safe parameterized queries using the callback pattern.

Key Terms

Install mysql2

Create the Database and Table (MySQL)

Run this in MySQL Workbench or the terminal before starting:

config/db.js — Creating the Connection

Environment Variables

Using db in app.js

How db.query() Works

All database operations use db.query(sql, params, callback):
Always check if (err) first inside the callback. If you skip this, a database error will crash the server with an unhandled exception.

Basic Query Examples

SELECT all rows

SELECT one row by ID

INSERT a row

UPDATE a row

DELETE a row

db.query() Result Object Reference

Why Use ? Placeholders

Never build SQL by concatenating user input:
A malicious user sending ' OR '1'='1 as the email would return all users with string concatenation. With ? placeholders, mysql2 escapes it and it becomes a literal string search.

Common Mistakes

require('dotenv').config() must come before require('./config/db'). Otherwise process.env.DB_PASS is undefined when the connection is created.
Every db.query() callback must start with if (err) { return res.status(500)... }. Skipping this means a DB error will crash the server instead of returning a clean response.
results is always an array. For single-row lookups always check results.length === 0 for not found, then use results[0] to access the row.
If the row does not exist, affectedRows is 0. Without this check you return 200 even though nothing happened. Always return 404 when affectedRows === 0.