Connecting to MySQL
The mysql2 package connects your Node app to a MySQL database and runs queries.
In this page:
Syntax
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
host: 'host', user: 'user', password: 'password', database: 'database'
});
const [rows] = await connection.execute('SELECT * FROM table_name WHERE column = ?', [value]);
Connecting to MySQL
Install mysql2, create a connection or pool with host, user, password and database, then call query or execute. Use placeholders (?) with execute to avoid SQL injection. Always close connections or use a pool.
Note:
Prepared statements with ? placeholders prevent SQL injection.
Example: Connecting to MySQL
$ npm install mysql2
const mysql = require("mysql2/promise");
const pool = mysql.createPool({ host: "localhost", user: "app", password: process.env.DB_PASS, database: "shop" });
const [rows] = await pool.execute("SELECT id, name FROM users WHERE id = ?", [1]);
console.log(rows[0]);
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Building SQL with string concatenation
- Not closing connections
- Hard-coding credentials
Chapter Summary
- Install mysql2
- Create a pool
- Use placeholders
- Close or reuse connections
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: