├── db.js ├── package.json ├── services └── employee.service.js ├── index.js ├── mysql script used.sql ├── controllers └── employee.controller.js └── README.md /db.js: -------------------------------------------------------------------------------- 1 | const mysql = require('mysql2/promise') 2 | 3 | const mysqlPool = mysql.createPool({ 4 | host: 'localhost', 5 | user: 'root', 6 | password: '1234', 7 | database: 'employee_db' 8 | }) 9 | 10 | 11 | module.exports = mysqlPool -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-mysql-crud", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "body-parser": "^1.20.2", 13 | "express": "^4.18.2", 14 | "express-async-errors": "^3.1.1", 15 | "mysql2": "^3.2.0" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /services/employee.service.js: -------------------------------------------------------------------------------- 1 | const db = require('../db') 2 | 3 | module.exports.getAllEmployees = async () => { 4 | const [records] = await db.query("SELECT * FROM employees") 5 | return records; 6 | } 7 | 8 | module.exports.getEmployeeById = async (id) => { 9 | const [[record]] = await db.query("SELECT * FROM employees WHERE id = ?", [id]) 10 | return record; 11 | } 12 | 13 | module.exports.deleteEmployee = async (id) => { 14 | const [{ affectedRows }] = await db.query("DELETE FROM employees WHERE id = ?", [id]) 15 | return affectedRows; 16 | } 17 | 18 | module.exports.addOrEditEmployee = async (obj, id = 0) => { 19 | const [[[{affectedRows}]]] = await db.query("CALL usp_employee_add_or_edit(?,?,?,?)", 20 | [id, obj.name, obj.employee_code, obj.salary]) 21 | return affectedRows; 22 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const express = require('express'), 2 | app = express(), 3 | bodyparser = require('body-parser'); 4 | require('express-async-errors') 5 | 6 | const db = require('./db'), 7 | employeeRoutes = require('./controllers/employee.controller') 8 | 9 | 10 | //middleware 11 | app.use(bodyparser.json()) 12 | app.use('/api/employees', employeeRoutes) 13 | app.use((err, req, res, next) => { 14 | console.log(err) 15 | res.status(err.status || 500).send('Something went wrong!') 16 | }) 17 | 18 | 19 | //first make sure db connection is successful 20 | //then start the express server. 21 | db.query("SELECT 1") 22 | .then(() => { 23 | console.log('db connection succeeded.') 24 | app.listen(3000, 25 | () => console.log('server started at 3000')) 26 | }) 27 | .catch(err => console.log('db connection failed. \n' + err)) 28 | -------------------------------------------------------------------------------- /mysql script used.sql: -------------------------------------------------------------------------------- 1 | -- create table 2 | CREATE TABLE `employee_db`.`employees` ( 3 | `id` int NOT NULL AUTO_INCREMENT, 4 | `name` varchar(45) DEFAULT NULL, 5 | `employee_code` varchar(45) DEFAULT NULL, 6 | `salary` int DEFAULT NULL, 7 | PRIMARY KEY (`id`) 8 | ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; 9 | 10 | -- insert 4 employee 11 | LOCK TABLES `employee_db`.`employees` WRITE; 12 | INSERT INTO `employee_db`.`employees` VALUES 13 | (1,'Samantha Mackenzie','EMP97',80000), 14 | (2,'Layla Benn','EMP91',92000), 15 | (3,'Luis Alberto','EMP99',84000), 16 | (4,'Rishaan','EMP70',85000); 17 | UNLOCK TABLES; 18 | 19 | -- stored procedure - execute withing create procedure window 20 | CREATE PROCEDURE `employee_db`.`usp_employee_add_or_edit` ( 21 | IN _id INT, 22 | IN _name VARCHAR(45), 23 | IN _employee_code VARCHAR(45), 24 | IN _salary INT 25 | 26 | ) 27 | BEGIN 28 | IF _id = 0 THEN 29 | INSERT INTO employees(name,employee_code,salary) 30 | VALUES (_name,_employee_code,_salary); 31 | 32 | ELSE 33 | UPDATE employees 34 | SET name = _name, 35 | employee_code = _employee_code, 36 | salary = _salary 37 | WHERE id = _id; 38 | END IF; 39 | 40 | SELECT ROW_COUNT() AS 'affectedRows'; 41 | END -------------------------------------------------------------------------------- /controllers/employee.controller.js: -------------------------------------------------------------------------------- 1 | const express = require('express'), 2 | router = express.Router() 3 | 4 | const service = require('../services/employee.service') 5 | 6 | //http://localhost:3000/api/employees/ 7 | router.get('/', async (req, res) => { 8 | const employees = await service.getAllEmployees() 9 | res.send(employees) 10 | }) 11 | 12 | router.get('/:id', async (req, res) => { 13 | const employee = await service.getEmployeeById(req.params.id) 14 | if (employee == undefined) 15 | res.status(404).json('no record with given id : ' + req.params.id) 16 | else 17 | res.send(employee) 18 | }) 19 | 20 | router.delete('/:id', async (req, res) => { 21 | const affectedRows = await service.deleteEmployee(req.params.id) 22 | if (affectedRows == 0) 23 | res.status(404).json('no record with given id : ' + req.params.id) 24 | else 25 | res.send('deleted successfully.') 26 | }) 27 | 28 | router.post('/', async (req, res) => { 29 | await service.addOrEditEmployee(req.body) 30 | res.status(201).send('created successfully.') 31 | }) 32 | 33 | router.put('/:id', async (req, res) => { 34 | const affectedRows = await service.addOrEditEmployee(req.body, req.params.id) 35 | if (affectedRows == 0) 36 | res.status(404).json('no record with given id : ' + req.params.id) 37 | else 38 | res.send('updated successfully.') 39 | }) 40 | 41 | 42 | 43 | module.exports = router; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MySQL-CRUD-with-Node.js-API 2 | MySQL CRUD with Node.js API 3 | 4 | ## How it works ? 5 | 6 | :tv: Video tutorial on this same topic 7 | Url : https://youtu.be/YkBOkV0s5eQ 8 | 9 | Video Tutorial for CRUD Operations with Node.js API and MySQL 12 | 13 | 14 | | :bar_chart: | List of Tutorials | | :moneybag: | Support Us | 15 | |--------------------------:|:---------------------|---|---------------------:|:-------------------------------------| 16 | | Angular |http://bit.ly/2KQN9xF | |Paypal | https://goo.gl/bPcyXW | 17 | | Asp.Net Core |http://bit.ly/30fPDMg | |Amazon Affiliate | https://geni.us/JDzpE | 18 | | React |http://bit.ly/325temF | | 19 | | Python |http://bit.ly/2ws4utg | | :point_right: | Follow Us | 20 | | Node.js |https://goo.gl/viJcFs | |Website |http://www.codaffection.com | 21 | | Asp.Net MVC |https://goo.gl/gvjUJ7 | |YouTube |https://www.youtube.com/codaffection | 22 | | Flutter |https://bit.ly/3ggmmJz| |Facebook |https://www.facebook.com/codaffection | 23 | | Web API |https://goo.gl/itVayJ | |Twitter |https://twitter.com/CodAffection | 24 | | MEAN Stack |https://goo.gl/YJPPAH | | 25 | | C# Tutorial |https://goo.gl/s1zJxo | | 26 | | Asp.Net WebForm |https://goo.gl/GXC2aJ | | 27 | | C# WinForm |https://goo.gl/vHS9Hd | | 28 | | MS SQL |https://goo.gl/MLYS9e | | 29 | | Crystal Report |https://goo.gl/5Vou7t | | 30 | | CG Exercises in C Program |https://goo.gl/qEWJCs | | 31 | --------------------------------------------------------------------------------