Lesson 41 of 50 – MySQL Connection in Node.js
82% Completed
82%

MySQL Connection in Node.js

Learn how to connect Node.js with MySQL, create databases and tables, insert records, retrieve data, update records, and delete records.

What is MySQL? MySQL is a relational database management system used to store and manage structured data. Node.js applications can communicate with MySQL using packages such as mysql2.

1. Why Connect Node.js with MySQL?

Node.js can handle application logic and API requests, while MySQL stores application data permanently.

Example Applications
  • Student management systems
  • Library management systems
  • Online admission systems
  • Course management applications
  • E-commerce websites
  • Fee and payment management systems

2. Requirements

Before connecting Node.js with MySQL, install the following:

  • Node.js and npm
  • MySQL Server
  • A code editor such as Visual Studio Code
  • MySQL Workbench or another MySQL client (optional)

Check your Node.js and npm installations:

node -v
npm -v
If both commands display version numbers, Node.js and npm are available in your terminal.

3. Create a Node.js Project

Create a folder named node-mysql-app.

mkdir node-mysql-app
cd node-mysql-app
npm init -y

The npm init -y command creates a default package.json file.

4. Install the MySQL2 Package

We will use the mysql2 package to connect Node.js with MySQL.

npm install mysql2
Why Use mysql2?
  • Connects Node.js applications to MySQL.
  • Supports callback and Promise-based APIs.
  • Supports prepared statements and parameterized queries.
  • Supports connection pooling.

5. Create a MySQL Database

Open your MySQL client and execute the following SQL command:

CREATE DATABASE school_db;

Select the database:

USE school_db;

Now create a table named students:

CREATE TABLE students (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) NOT NULL UNIQUE,
    course VARCHAR(100) NOT NULL
);
Table Structure
Column Data Type Purpose
id INT Unique student ID generated automatically.
name VARCHAR(100) Student name.
email VARCHAR(150) Unique student email address.
course VARCHAR(100) Student course name.

6. Connect Node.js with MySQL

Create a file named db.js in your project folder.

db.js
const mysql = require("mysql2/promise");

const pool = mysql.createPool({
    host: "localhost",
    user: "YOUR_MYSQL_USER",
    password: "YOUR_MYSQL_PASSWORD",
    database: "school_db",
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

module.exports = pool;

Replace the following values with your MySQL credentials:

  • YOUR_MYSQL_USER – your MySQL username.
  • YOUR_MYSQL_PASSWORD – your MySQL password.
Security note: For real applications, store database credentials in environment variables rather than committing them directly to source code. Use a dedicated database user with only the permissions the application needs.

7. Test the MySQL Connection

Create a file named test-db.js.

const pool = require("./db");

async function testConnection() {
    try {
        const connection = await pool.getConnection();

        console.log("MySQL connected successfully!");

        connection.release();
    } catch (error) {
        console.error("MySQL connection failed:", error.message);
    } finally {
        await pool.end();
    }
}

testConnection();

Run the file:

node test-db.js
Expected output:
MySQL connected successfully!

8. Insert Data into MySQL

We can insert a student into the database using an SQL INSERT query.

const pool = require("./db");

async function addStudent() {
    try {
        const sql = `
            INSERT INTO students (name, email, course)
            VALUES (?, ?, ?)
        `;

        const values = [
            "Rahul Kumar",
            "rahul@example.com",
            "Node.js"
        ];

        const [result] = await pool.execute(sql, values);

        console.log("Student added successfully!");
        console.log("Student ID:", result.insertId);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await pool.end();
    }
}

addStudent();
Important Explanation
  • pool.execute() executes the SQL statement.
  • The question marks are placeholders for parameter values.
  • result.insertId returns the generated student ID.
Parameterized queries help prevent SQL injection by keeping user-supplied values separate from SQL statement text.

9. Retrieve Data from MySQL

Use the SQL SELECT statement to retrieve all students.

const pool = require("./db");

async function getStudents() {
    try {
        const [rows] = await pool.execute(
            "SELECT id, name, email, course FROM students"
        );

        console.log(rows);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await pool.end();
    }
}

getStudents();
Example Output
[
  {
    id: 1,
    name: 'Rahul Kumar',
    email: 'rahul@example.com',
    course: 'Node.js'
  }
]

The returned rows value is an array containing the matching database records.

10. Retrieve a Student by ID

To retrieve one student, use a parameterized query with a WHERE condition.

const pool = require("./db");

async function getStudentById(id) {
    try {
        const [rows] = await pool.execute(
            "SELECT id, name, email, course FROM students WHERE id = ?",
            [id]
        );

        if (rows.length === 0) {
            console.log("Student not found");
            return;
        }

        console.log(rows[0]);
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await pool.end();
    }
}

getStudentById(1);
Remember: WHERE id = ? selects a matching record. The value 1 is passed separately as a query parameter.

11. Update Data in MySQL

Use the SQL UPDATE statement to change an existing record.

const pool = require("./db");

async function updateStudent() {
    try {
        const [result] = await pool.execute(
            "UPDATE students SET course = ? WHERE id = ?",
            ["Full Stack Development", 1]
        );

        if (result.affectedRows === 0) {
            console.log("Student not found or no changes made");
        } else {
            console.log("Student updated successfully!");
        }
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await pool.end();
    }
}

updateStudent();
Always use an appropriate WHERE condition in an UPDATE statement. Without it, every record in the table could be updated.

12. Delete Data from MySQL

Use the SQL DELETE statement to remove a record.

const pool = require("./db");

async function deleteStudent() {
    try {
        const [result] = await pool.execute(
            "DELETE FROM students WHERE id = ?",
            [1]
        );

        if (result.affectedRows === 0) {
            console.log("Student not found");
        } else {
            console.log("Student deleted successfully!");
        }
    } catch (error) {
        console.error("Error:", error.message);
    } finally {
        await pool.end();
    }
}

deleteStudent();
Warning: DELETE permanently removes matching rows unless you use a transaction or have a suitable recovery mechanism. Always verify the ID and WHERE condition before deleting records.

13. Connect MySQL with Express.js

Now let's build a small REST API that retrieves student data from MySQL.

Create a file named server.js.

server.js
const express = require("express");
const pool = require("./db");

const app = express();

app.use(express.json());

// GET all students
app.get("/students", async (req, res) => {
    try {
        const [rows] = await pool.execute(
            "SELECT id, name, email, course FROM students"
        );

        res.json(rows);
    } catch (error) {
        console.error(error);

        res.status(500).json({
            message: "Unable to retrieve students"
        });
    }
});

// GET one student
app.get("/students/:id", async (req, res) => {
    try {
        const id = Number(req.params.id);

        if (!Number.isInteger(id) || id <= 0) {
            return res.status(400).json({
                message: "Invalid student ID"
            });
        }

        const [rows] = await pool.execute(
            "SELECT id, name, email, course FROM students WHERE id = ?",
            [id]
        );

        if (rows.length === 0) {
            return res.status(404).json({
                message: "Student not found"
            });
        }

        res.json(rows[0]);
    } catch (error) {
        console.error(error);

        res.status(500).json({
            message: "Unable to retrieve student"
        });
    }
});

// POST a student
app.post("/students", async (req, res) => {
    try {
        const { name, email, course } = req.body;

        if (
            typeof name !== "string" || !name.trim() ||
            typeof email !== "string" || !email.trim() ||
            typeof course !== "string" || !course.trim()
        ) {
            return res.status(400).json({
                message: "Name, email, and course are required"
            });
        }

        const [result] = await pool.execute(
            `INSERT INTO students (name, email, course)
             VALUES (?, ?, ?)`,
            [name.trim(), email.trim(), course.trim()]
        );

        res.status(201).json({
            message: "Student added successfully",
            id: result.insertId
        });
    } catch (error) {
        if (error.code === "ER_DUP_ENTRY") {
            return res.status(409).json({
                message: "Email already exists"
            });
        }

        console.error(error);

        res.status(500).json({
            message: "Unable to add student"
        });
    }
});

const PORT = 5000;

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Install Express if you have not already installed it:

npm install express

Start your API:

node server.js
Your Express API is now connected to MySQL and can retrieve, search for, and insert student records.

14. Test the MySQL API Using Postman

Method URL Purpose
GET /students Retrieve all students.
GET /students/1 Retrieve student ID 1.
POST /students Add a student.

Use http://localhost:5000 as the base URL. For POST requests, select Body → raw → JSON.

{
    "name": "Priya Sharma",
    "email": "priya@example.com",
    "course": "React"
}

Send the request and check the response status code and JSON output. The new record should also appear in the MySQL table.

15. Common MySQL Connection Errors

Error Possible Solution
Access denied Verify the MySQL username, password, and permissions.
Unknown database Confirm that school_db exists.
ECONNREFUSED Check whether MySQL is running and the host and port are correct.
Table doesn't exist Create the students table in the correct database.
Duplicate entry Use a different email because the email column is unique.
Cannot find module Run npm install mysql2 in the project directory.

16. Practical Assignment

Student Management API

Create a student management API using Node.js, Express.js, and MySQL.

  1. Create a database named school_db.
  2. Create a students table.
  3. Connect Node.js to MySQL using mysql2.
  4. Create a GET route to list all students.
  5. Create a GET route to retrieve one student by ID.
  6. Create a POST route to add a student.
  7. Add validation for required fields.
  8. Handle duplicate email errors.
  9. Test your API using Postman.

Bonus Task: Add PUT and DELETE routes and test them with Postman.

17. Lesson Summary

In this lesson, you learned how to install mysql2, create a MySQL database and table, connect Node.js to MySQL, perform CRUD operations, build Express API endpoints, and test those endpoints using Postman.

Test Your Knowledge – MySQL in Node.js

Select the correct answer for each question.

1. Which package is used in this lesson to connect Node.js with MySQL?
2. Which SQL statement is used to retrieve records?
3. Why should we use parameterized SQL queries?