How to Connect to MySQL in Node.js: Simple Guide
To connect to MySQL in Node.js, use the
mysql2 library by creating a connection with your database credentials using mysql.createConnection(). Then call connection.connect() to establish the connection before running queries.Syntax
Here is the basic syntax to connect to a MySQL database in Node.js using the mysql2 library:
mysql.createConnection(config): Creates a connection object with your database details.connection.connect(callback): Opens the connection and handles errors.connection.query(sql, params, callback): Runs SQL queries.connection.end(): Closes the connection when done.
javascript
import mysql from 'mysql2'; const connection = mysql.createConnection({ host: 'localhost', user: 'your_username', password: 'your_password', database: 'your_database' }); connection.connect(error => { if (error) { console.error('Connection failed:', error); return; } console.log('Connected to MySQL!'); });
Example
This example shows how to connect to MySQL, run a simple query to get all rows from a table called users, and then close the connection.
javascript
import mysql from 'mysql2'; const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password123', database: 'testdb' }); connection.connect(error => { if (error) { console.error('Connection error:', error); return; } console.log('Connected to MySQL!'); connection.query('SELECT * FROM users', (err, results) => { if (err) { console.error('Query error:', err); } else { console.log('Users:', results); } connection.end(); }); });
Output
Connected to MySQL!
Users: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]
Common Pitfalls
Common mistakes when connecting to MySQL in Node.js include:
- Not installing or importing the
mysql2library. - Using wrong or missing database credentials.
- Forgetting to call
connection.connect()before queries. - Not closing the connection with
connection.end(), which can cause resource leaks. - Not handling errors in callbacks, leading to silent failures.
javascript
import mysql from 'mysql2'; // Wrong: Missing connect call const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'wrongpass', database: 'testdb' }); connection.query('SELECT 1', (err, results) => { if (err) { console.error('Error:', err); } else { console.log('Result:', results); } }); // Right: Always connect first and handle errors const connection2 = mysql.createConnection({ host: 'localhost', user: 'root', password: 'correctpass', database: 'testdb' }); connection2.connect(error => { if (error) { console.error('Connection failed:', error); return; } connection2.query('SELECT 1', (err, results) => { if (err) { console.error('Query error:', err); } else { console.log('Result:', results); } connection2.end(); }); });
Quick Reference
Remember these key points when connecting to MySQL in Node.js:
- Use
mysql2library for modern, maintained support. - Always call
connection.connect()before queries. - Handle errors in both connection and query callbacks.
- Close connections with
connection.end()to free resources. - Use environment variables to keep credentials safe.
Key Takeaways
Use the mysql2 library and create a connection with your database details.
Always call connection.connect() before running queries to establish the connection.
Handle errors in connection and query callbacks to avoid silent failures.
Close the connection with connection.end() to prevent resource leaks.
Keep your database credentials secure, ideally using environment variables.