Lesson 4 of 6By Simplilearn
Last updated on Aug 7, 20207882Node.js is an extremely popular open-source, cross-platform web, and network app development resource. Thousands of developers around the world use it daily to develop I/O intensive web applications such as video streaming sites, single-page applications, online chat applications, and other web apps. Built on Google Chrome's JavaScript-based runtime environment, Node.js brings many advantages to the table, making it a better choice than other server-side platforms like Java or PHP.
This Node.js MySQL Tutorial will help you learn how to connect your webserver to a MySQL database. First, we'll learn the basic concepts of MySQL, and then we will create our web application. The application will enable us to add, edit, and delete employees in a MySQL database, and we can view the changes through the Postman application or phpMyAdmin.
There are several points that more than justify connecting Node.js with MySQL for data storage:
![]() |
|
![]() |
|
![]() |
|
![]() |
|
For the next part of our tutorial, we are going to learn how to create and manage an employee database.
1. Download Node.js from https://nodejs.org/en/download/. Select the installer that is compatible with your operating system and environment.
Fig: Node.js download page
2. Run the Node.js installer and accept the license agreement. You can leave the other settings in default mode. The installer will install Node.js and prompt you to click on the finish button.
Fig: Node.js setup
3. Verify that Node.js was properly installed by opening the command prompt and typing this command: node --version
Fig: Node.js verification
4. When we install Node.js, we gain access to NPM (Node Package Manager). NPM includes many libraries that are used in web applications such as React. Verify whether it is installed or not with the following command in CMD: npm --version
Fig: NPM verification
Install the text editor of your choice. We are using Visual Studio Code in this tutorial, but you can also use other editors—like Atom and Sublime Text—if you are more comfortable with them.
Fig: Visual Studio Code download page
Similar to Node.js installation, you can download the MongoDB Community Server from its official website. Then, open the installer to install MySQL on your system, keeping the default settings.
For this tutorial, we are using the Postman application to work with the API requests in our code.
To download the application, go to its official website.
Fig: VS Code project
We are going to connect the Node.js web server with the MySQL database to store the employee details. The code that we’re writing now will allow us to create the employee database. We will be able to create, update, and delete employees in the database.
Learn to build network applications quickly and efficiently using JavaScript with the Node.js Training. Click to enroll now!
Let’s first take a look at how the project directory should look at the end of this tutorial. We are working only on a single file called index.js, so the project directory is very simple.
Create a file called index.js in the project directory. Since our main goal is to understand the connection between Node.js and MySQL database, this will be the only file that we create and work on in this project.
So let’s go ahead and explore what each snippet of code does in this file.
const express = require("express");
const mysql = require("mysql");
// Create connection
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "simplilearn",
database: "nodemysql",
});
// Connect to MySQL
db.connect((err) => {
if (err) {
throw err;
}
console.log("MySql Connected");
});
const app = express();
// Create DB
app.get("/createdb", (req, res) => {
let sql = "CREATE DATABASE nodemysql";
db.query(sql, (err) => {
if (err) {
throw err;
}
res.send("Database created");
});
});
// Create table
app.get("/createemployee", (req, res) => {
let sql =
"CREATE TABLE employee(id int AUTO_INCREMENT, name VARCHAR(255), designation VARCHAR(255), PRIMARY KEY(id))";
db.query(sql, (err) => {
if (err) {
throw err;
}
res.send("Employee table created");
});
});
// Insert employee 1
app.get("/employee1", (req, res) => {
let post = { name: "Jake Smith", designation: "Chief Executive Officer" };
let sql = "INSERT INTO employee SET ?";
let query = db.query(sql, post, (err) => {
if (err) {
throw err;
}
res.send("Employee 1 added");
});
});
// Update employee
app.get("/updateemployee/:id", (req, res) => {
let newName = "Updated name";
let sql = `UPDATE employee SET name = '${newName}' WHERE id = ${req.params.id}`;
let query = db.query(sql, (err) => {
if (err) {
throw err;
}
res.send("Post updated...");
});
});
// Delete employee
app.get("/deleteemployee/:id", (req, res) => {
let sql = `DELETE FROM employee WHERE id = ${req.params.id}`;
let query = db.query(sql, (err) => {
if (err) {
throw err;
}
res.send("Employee deleted");
});
});
app.listen("3000", () => {
console.log("Server started on port 3000");
});
app.listen("3000", () => {
console.log("Server started on port 3000");
});
That’s all we need to do r to connect our Node.js web server with MySQL database. We can now run the application using the terminal in the VS Code. Use the command node index.js to start the web server.
The terminal should look like this if the server was started without any issue.
If your terminal also displays “server started”, it means that the server is running properly.
To use the API requests that we have defined in the application code, use the Postman application. Fill in the appropriate request for each task that you want to perform and hit the Send button to send the filled-in request.
If you have any problems following any step in this tutorial, please feel free to use the comments section below and get your questions answered.
Now that you know how to connect Node.js to MySQL database, you may wonder how you can gain the skills necessary to take advantage of its rising popularity, either by upskilling or trying for a new career altogether. Fortunately, there are some great options available for learning this exciting and practical skill set at your own pace.
Simplilearn's Node.js Certification training course will give you a great foundation and solid understanding of this popular platform. It combines live, instructor-led training, self-paced tutorials, and hands-on projects to help you become career-ready. Get started today and seize your future!
Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.
Node.js Express Tutorial: Create a User Management System
2020 Trends in Data Science
MongoDB vs MySQL: Which Database is Better and Why?
JavaScript DOM Tutorial: 2020 Edition
React With Redux Tutorial: Learn the Basics
The Comprehensive Ethical Hacking Guide for Beginners