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 usedb.query(sql, params, callback):
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:
' 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
Not requiring dotenv before db.js
Not requiring dotenv before db.js
require('dotenv').config() must come before require('./config/db'). Otherwise process.env.DB_PASS is undefined when the connection is created.Forgetting to check err in callbacks
Forgetting to check err in callbacks
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.Using results directly for a SELECT expecting one row
Using results directly for a SELECT expecting one row
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.Not checking affectedRows on UPDATE/DELETE
Not checking affectedRows on UPDATE/DELETE
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.