Category: nodejs
connect MySQL for Node.js using npm.
Published on 02 Jun 2026
Explanation
Install the MySQL package for Node.js
using npm.
Code:
npm install mysql2
Explanation
Import the mysql2 package and create
a connection object with database
credentials.
Code:
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
Explanation
Connect to the MySQL database and
verify the connection.
Code:
connection.connect((err) => {
if (err) {
console.error('Connection failed:', err);
return;
}
console.log('Connected to MySQL');
});
Explanation
Execute a SELECT query to fetch
records from a table.
Code:
connection.query('SELECT * FROM users',
(err, results) => {
if (err) {
console.error(err);
return;
}
console.log(results);
});
Explanation
Close the database connection after
completing
operations.
Code:
connection.end((err) => {
if (err) {
console.error(err);
return;
}
console.log('Connection closed');
});