Node.js — MySQL
Installation
npm install mysql2
Connection
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb',
waitForConnections: true,
connectionLimit: 10
});
Querying
// Simple query
const [rows] = await pool.execute('SELECT * FROM users');
// Parameterized query
const [rows] = await pool.execute(
'SELECT * FROM users WHERE id = ?',
[userId]
);
// Insert
await pool.execute(
'INSERT INTO users (name, email) VALUES (?, ?)',
['John', 'john@example.com']
);
CRUD Operations
// Read
const [users] = await pool.execute('SELECT * FROM users');
// Create
await pool.execute(
'INSERT INTO users (name, email) VALUES (?, ?)',
[name, email]
);
// Update
await pool.execute(
'UPDATE users SET name = ? WHERE id = ?',
[name, id]
);
// Delete
await pool.execute('DELETE FROM users WHERE id = ?', [id]);
Error Handling
try {
const [rows] = await pool.execute('SELECT * FROM users');
} catch (err) {
console.error('Database error:', err.message);
}
Mini Practice
- Set up MySQL connection pool
- Perform CRUD operations
- Use parameterized queries
- Handle database errors
Up Next
Continue with MongoDB — MongoDB integration.
Related Topics
Frequently Asked Questions about MySQL
What is MySQL in Node.js?
MySQL is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn MySQL?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn MySQL.
Why is MySQL important in Node.js?
MySQL is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.