Hackforge Academy

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();

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community