MySQL remains one of the most widely deployed relational databases, and mysql2 is the standard driver for connecting it to a Node.js/Express app. This lesson covers connection pooling and safe, parameterized queries.
Connecting With mysql2
mysql2 is a modern MySQL driver for Node.js, largely compatible with the older mysql package's API but faster and with built-in Promise support. Like other drivers, you should create a connection pool once at startup rather than a single connection per request.
Every query with user-supplied values must use parameterized placeholders (?), never string concatenation, to prevent SQL injection.
When multiple related writes must all succeed or all fail together (like debiting one account and crediting another), wrap them in a transaction using a single connection checked out from the pool.
const connection = await pool.getConnection();
try {
await connection.beginTransaction();
await connection.query('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, fromId]);
await connection.query('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, toId]);
await connection.commit();
} catch (err) {
await connection.rollback();
throw err;
} finally {
connection.release();
}
Common Mistakes
Building SQL queries with string concatenation or template literals, opening the door to SQL injection.
Opening a new connection per request instead of using a shared pool.
Forgetting connection.release() after manually checking out a connection for a transaction.
Not wrapping multi-step writes in a transaction, risking partial, inconsistent updates.
Key Takeaways
mysql2/promise provides an async/await-friendly driver for MySQL in Node.js.
Always use ? parameterized placeholders instead of string-building queries.
A connection pool, created once at startup, should back all your queries.
Wrap related multi-step writes in a transaction to keep them atomic.
Pro Tip
Never string-interpolate a value into SQL, even one you "trust", parameterized queries cost nothing extra to write and eliminate an entire class of SQL injection vulnerabilities permanently.
You now know how to connect Express to MySQL safely. Next, learn PostgreSQL with the pg driver in the PostgreSQL with Express lesson.