Hackforge Academy

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');
});

πŸš€ 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