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

npm install mysql2

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 PracticeWhy
Use mysql2 + promise APIModern, async/await
Use connection poolFaster, scalable
Use prepared statementsPrevent SQL Injection
Store credentials in .envSecurity
Wrap queries in try/catchError safety
Validate inputsPrevent errors & attacks

You may also like...