Category: nodejs
connect Node.js with MySQL
Published on 05 Mar 2026
Explanation
Initialize a Node.js project and
install the mysql2
package to connect Node.js with MySQL.
Code:
npm init -y npm install mysql2
Explanation
Import the mysql2 module to use
MySQL features in your Node.js app.
Code:
const mysql = require('mysql2');
Explanation
Create a connection object by providing
host
username,
password,
database name.
Code:
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'testdb'
});
Explanation
Establish the connection and handle any
connection errors.
Code:
connection.connect((err) => {
if (err) {
console.error('Connection failed:');
return;
}
console.log('Connected to MySQL success!');
});
Explanation
Execute a SQL query to fetch data from
the users table.
Code:
connection.query('SELECT * FROM users',
(err, results) => {
if (err) throw err;
console.log(results);
});
Explanation
Close the MySQL connection
after completing database operations
to avoid memory leaks.
Code:
connection.end();