Node.js MySQL Delete Query with Example
Before starting the coding, You must set up the following things
- You have to Install Basic Express Application like the following project folder structure
myapp/ |__bin |__node_modules |__public |__routes/ | |__index.js | |__user.js |__views/ | |__index.ejs | |__user.ejs | |__user-list.ejs |__app.js |__database.js |__package-lock.json |__package.json
- Create
database.js
file and write the following Node.js MySQL connection Query.
- var mysql = require('mysql');
- var conn = mysql.createConnection({
- host: 'localhost', // Replace with your host name
- user: 'root', // Replace with your database username
- password: '', // Replace with your database password
- database: 'nodeapp' // // Replace with your database Name
- });
- conn.connect(function(err) {
- if (err) throw err;
- console.log('Database is connected successfully !');
- });
- module.exports = conn;
Write SQL Query in Node.js to Delete Data
Use the following script in the
routes/user.js
file. This script will help you to delete data from the users
table and display it in HTML form.- router.get('/delete/:id', function(req, res, next) {
- var id= req.params.id;
- var sql = 'DELETE FROM users WHERE id = ?';
- db.query(sql, [id], function (err, data) {
- if (err) throw err;
- console.log(data.affectedRows + " record(s) updated");
- });
- res.redirect('/user/user-list');
- });
Complete Script
Include the database connection file
database.js
in the routes/user.js
file.- var db=require('../database');
You can the following complete script in
routes/user.js
file.
Now, Include
routes/user.js
file in the root file app.js
- var userRouter = require('./routes/user');
- app.use('/user',userRouter);
File Name: routes/user.js
- var express = require('express');
- var router = express.Router();
- var db=require('../database');
- // another script like create, select , update route will be defined here
- router.get('/delete/:id', function(req, res, next) {
- var id= req.params.id;
- var sql = 'DELETE FROM users WHERE id = ?';
- db.query(sql, [id], function (err, data) {
- if (err) throw err;
- console.log(data.affectedRows + " record(s) updated");
- });
- res.redirect('/user/user-list');
- });
- module.exports = router;
Comments
Post a Comment