Node.js is a popular open-source JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to easily build scalable server-side applications. In this tutorial, we will focus on using Node.js with MySQL to perform CRUD operations, including GET, POST, PUT, and DELETE.
Prerequisites:
- Basic knowledge of Node.js and MySQL
- Node.js installed on your machine
- MySQL installed on your machine
- MySQL workbench or any other MySQL client for database operations
Step 1: Setting up the Node.js project
-
Create a new directory for your project and navigate into it.
mkdir node-mysql-crud cd node-mysql-crud
-
Initialize a new Node.js project.
npm init -y
-
Install required dependencies.
npm install express mysql body-parser
- Create a new file named
app.js
and require the necessary modules.const express = require('express'); const mysql = require('mysql'); const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Step 2: Setting up the MySQL database
1. Create a new MySQL database and a table.
```sql
CREATE DATABASE node_mysql_crud;
USE node_mysql_crud;
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
email VARCHAR(255)
);
- Connect to the MySQL database in your
app.js
file.const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'node_mysql_crud' });
connection.connect((err) => {
if (err) {
console.error(‘Error connecting to MySQL: ‘ + err.stack);
return;
}
console.log(‘Connected to MySQL as id ‘ + connection.threadId);
});
Step 3: Implementing CRUD operations
1. Implement GET operation to fetch all users.
```javascript
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
res.send(results);
});
});
-
Implement POST operation to create a new user.
app.post('/users', (req, res) => { const { name, email } = req.body; connection.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (err, results) => { if (err) throw err; res.send('User added successfully'); }); });
-
Implement PUT operation to update an existing user.
app.put('/users/:id', (req, res) => { const id = req.params.id; const { name, email } = req.body; connection.query('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id], (err, results) => { if (err) throw err; res.send('User updated successfully'); }); });
- Implement DELETE operation to delete a user.
app.delete('/users/:id', (req, res) => { const id = req.params.id; connection.query('DELETE FROM users WHERE id = ?', [id], (err, results) => { if (err) throw err; res.send('User deleted successfully'); }); });
Step 4: Running the Node.js server
-
Start the Node.js server by running the following command.
node app.js
- You can now access your API endpoints using tools like Postman or your web browser.
- GET: http://localhost:3000/users
- POST: http://localhost:3000/users (with name and email in the request body)
- PUT: http://localhost:3000/users/:id (with name and email in the request body)
- DELETE: http://localhost:3000/users/:id
Congratulations! You have successfully implemented CRUD operations using Node.js and MySQL. You can now build more complex applications using these concepts.
https://goo.gl/RFY5C2 : Subscribe to CodAffection
https://goo.gl/bPcyXW : Buy me a Coffee
http://bit.ly/2HwIEqF : Node.js + React.js CRUD
http://bit.ly/2ZaM5cU : Node.js + ExpressHandlebars CRUD
https://bit.ly/3PGXsp5 : Node.js + MongoDB CRUD
https://bit.ly/3Ktqess : MEAN Stack CRUD (Node + Angular)
Thanks a lot!
Your work is really appreciated mate!
Thanks for sharing……
Damn you're really good bro. 👍👍👍👍
see how you explained SQL injection in such a simple and perfect way within 15 seconds.
Hi Buddy,
Which user & password I need to use in mysqlPool?
const mysqlPool = mysql.createPool({
host: 'localhost',
user: 'root', ==> ??
password: '1234', ===> ??
database: 'employee_db'
})
which extension you are using for auto completion
How to Integrate/call this with html, to display the data in the webpage.!?
Wow, thanks for giving us better skills like this, 👏👏👏👏
Thanks for the video! "Boom" 😀
great explanation
Great man… Easy pizzy
Damn, you're good—Now, I want to try to add this to a web interface.
Crack! More than ten tutorials and this one worked!!!!
When I trying to Insert user into the user table by post , alwys says undefine the body of the req
¡Gracias!
thank you bro
great work thanks a lot
Hi,
I saw the video which is so good, Is it possible for you to post a video with typescript implementation for the same CRUD operation.
and authorization validation process
Great work guy! This helped me a bunch! <3<3<3