Node.js MySQL
🌐 Node.js MySQL – Complete Guide
MySQL is one of the most widely used relational databases, and Node.js connects to it efficiently using libraries like:
mysql (older, callback-based)
mysql2 (modern, supports promises & prepared statements)
👉 Recommended: mysql2 (fast, secure, supports async/await)
✅ 1. Install MySQL Library
✅ 2. Create a MySQL Connection
Using mysql2 (Promise-based)
✅ 3. Create a Connection Pool (Recommended)
A pool improves performance for real applications.
✅ 4. Run SQL Queries
SELECT Query
✅ 5. INSERT Query
✅ 6. UPDATE Query
✅ 7. DELETE Query
✅ 8. Use Prepared Statements (Safe for Production)
Prevents SQL Injection.
✅ 9. Using Node.js + Express + MySQL Example
server.js
✅ 10. MySQL Table Structure Example
✅ 11. Error Handling Example
✅ 12. Environment Variables (Best Practice)
Use .env file:
Node.js usage:
🎯 13. Best Practices
| Best Practice | Why |
|---|---|
Use mysql2 + promise API | Modern, async/await |
| Use connection pool | Faster, scalable |
| Use prepared statements | Prevent SQL Injection |
Store credentials in .env | Security |
| Wrap queries in try/catch | Error safety |
| Validate inputs | Prevent errors & attacks |
