📌 Introduction
Now that you understand how to work with Express routes and middleware,
It’s time to connect Node.js to a real database — MySQL.
In this beginner tutorial, you will learn how to:
-
Connect Node.js to a MySQL database
-
Run basic SQL queries
-
Build simple CRUD (Create, Read, Update, Delete) API routes
-
Test APIs using Postman
This guide is written step by step and is perfect for beginners.
✅ Prerequisites
Before starting, make sure you have the following installed:
-
Node.js and npm
-
MySQL running locally
-
Default user:
root
-
-
A MySQL database named testdb
Create Database & Table
Run the following commands in your MySQL terminal:
📁 Step 1 — Set Up the Project
Create a new project folder and move into it:
Initialize the project and install dependencies:
Create the main application file:
🔌 Step 2 — Connect Node.js to MySQL
Open app.js and add the following code:
Run the application:
Output:
➕ Step 3 — Insert Data (POST)
Add a route to insert a new user:
Test with Postman
POST → http://localhost:3000/users
Body (JSON):
Response:
📥 Step 4 — Get All Users (GET)
Add the GET route:
Test:
GET → http://localhost:3000/users
Response:
✏ Step 5 — Update User (PUT)
Add the update route:
Test:
PUT → http://localhost:3000/users/1
Body (JSON):
❌ Step 6 — Delete User (DELETE)
Add the delete route:
Test:
DELETE → http://localhost:3000/users/1
Response:
📄 Step 7 — Full app.js File
🧠 Summary
In this tutorial, you learned how to:
-
Connect Node.js to a MySQL database
-
Perform CRUD operations (Create, Read, Update, Delete)
-
Use prepared SQL queries
-
Build RESTful APIs with Express
-
Test APIs step by step using Postman

