Connecting to MySQL with mysql2
Overview
The mysql2
package is a popular MySQL client for Node.js that supports Promises and provides a simple API to interact with MySQL databases.
Installing mysql2
You can install the mysql2 package using npm. Run the following command:
npm install mysql2
Creating a Connection
Here‘s how to create a connection to your MySQL database:
const mysql = require('mysql2');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'yourUsername',
password: 'yourPassword',
database: 'yourDatabase'
});
// Connect to the database
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.stack);
return;
}
console.log('Connected to the MySQL database as ID', connection.threadId);
});
In this example, replace yourUsername
, yourPassword
, and yourDatabase
with your actual database credentials.
Querying the Database
You can easily execute SQL queries using the connection:
// Example of a SQL query
const sql = 'SELECT * FROM users';
connection.query(sql, (err, results) => {
if (err) throw err;
console.log('Results:', results);
});
This code executes a SQL query to select all users from the users
table and logs the results.
Closing the Connection
It's important to close the connection when you're done:
// Close the connection
connection.end((err) => {
if (err) {
return console.log('Error ending the connection:', err.message);
}
console.log('Connection to the database closed.');
});