Home » Node.js

Delete data from MYSQL table by using Node.js

In this article, we are going to learn how to delete a record from MYSQL table using Node.js server?
Submitted by Manu Jemini, on November 23, 2017

Prerequisite:

In this article, we want to delete a particular record from our table clients, so prepare a server file of node.js where we require the mysql module to work with mysql and after that, we prepare a connection by using mysql.createConnection() method of mysql module.

There are certain things that we have to define inside our create connection method like host, user, password and database name.

As, we are all set to go with our connection, all we need to create a SQL query to delete data basically a delete query and a field of that particular record after that we can use query() method to execute query statement with a callback function in which we can throw error if any and print the message where we can show the number of affected rows.

Database details:

  • Hostname: localhost
  • Port number: 3306
  • Username: root
  • Password: 123
  • Database: demo
  • Table name: clients
  • Field: address

Note: For deleting the record in a table we must have at least one field name.

Server File

//step-1
var mysql = require('mysql');

//step-2
var con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "123",
  database: "demo"
});

//step-3
con.connect(function(err) {
  if (err) throw err;
  var sql = "DELETE FROM clients WHERE address = 'Mumbai'";

//step-4
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Number of records deleted: " + result.affectedRows);
  });
});

Discussing steps that we have followed in our server file:

  • Require MySQL module.
  • Create Connection variable using mysql.createConnection() method.
  • Connect by using con.connect() method.
  • Creating SQL select query.
  • Execute query by using .query() method.

Output/result

Node.js - Delete data from table

Node.js - Delete data from table

If you have any query do comment.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.