nodejs
  1. nodejs-mysql-delete-record

Node.js MySQL Delete Record

In Node.js, you can easily delete a record from a MySQL database using the mysql module. In this tutorial, we will show you how to delete a record from a MySQL database using Node.js.

Syntax

The basic syntax for deleting a record from a MySQL database in Node.js using the mysql module is as follows:

connection.query('DELETE FROM table_name WHERE condition', function (error, results, fields) {
   if (error) throw error;
   console.log('Record deleted successfully!');
});

In the above example, you need to replace the table_name with the name of the table from which you want to delete the record, and the condition with the condition to be used for deleting the record.

Example

Let's consider a table named "customers" with the following data:

+----+-----------+-----+------+
| id | name      | age | city |
+----+-----------+-----+------+
| 1  | John      | 30  | Paris|
| 2  | Alice     | 25  | Tokyo|
| 3  | Bob       | 40  | Berlin|
| 4  | Claire    | 32  | London|
+----+-----------+-----+------+

Now, we want to delete the record where the name is "Alice". Here is how we can do it in Node.js:

const mysql = require('mysql');
const connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mydb'
});
 
connection.connect();
 
const query = "DELETE FROM customers WHERE name = 'Alice'";
 
connection.query(query, function (error, results, fields) {
   if (error) throw error;
   console.log('Record deleted successfully!');
});
 
connection.end();

Output

When you execute the above example, you should see output similar to the following:

Record deleted successfully!

Explanation

In the above example, we first created a database connection using the mysql module. We then defined a query to delete the record where the name is "Alice". We executed the query using the query() function of the connection object.

Finally, we closed the database connection using the end() method.

Use

You can use the DELETE statement provided by MySQL to delete records from a table when using Node.js and the mysql module.

Important Points

  • Be sure to use a condition in the DELETE statement, otherwise, all records in the table will be deleted.
  • Sanitize user inputs to prevent SQL injection attacks.

Summary

In this tutorial, we demonstrated how to delete a record from a MySQL database in Node.js. We covered the syntax, example, output, explanation, use, and important points for deleting a record from a MySQL database in Node.js. With this knowledge, you can now delete records from a MySQL database in Node.js using the mysql module.

Published on: