nodejs delete in mysql
To delete data from a MySQL database using Node.js, you can follow these steps:
- Install the MySQL module: First, you need to install the MySQL module for Node.js. You can do this by running the following command in your terminal:
npm install mysql
- Require the module: In your Node.js application, require the MySQL module using the
require
keyword:
const mysql = require('mysql');
- Create a connection: Establish a connection to the MySQL database by creating a connection object. Provide the necessary database connection details, such as host, user, password, and database name:
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
- Connect to the database: Connect to the MySQL database using the
connect
method of the connection object:
connection.connect((error) => {
if (error) throw error;
console.log('Connected to the MySQL server.');
});
- Delete data: Use the
query
method of the connection object to execute a DELETE statement. Pass the DELETE statement as a string parameter to thequery
method:
const deleteQuery = 'DELETE FROM table_name WHERE condition';
connection.query(deleteQuery, (error, result) => {
if (error) throw error;
console.log('Data deleted:', result);
});
In the code above, replace table_name
with the name of the table from which you want to delete data. Also, update the condition
with the appropriate condition for deleting specific rows.
- Close the connection: After executing the delete query, close the connection to the MySQL server using the
end
method of the connection object:
connection.end((error) => {
if (error) throw error;
console.log('Connection closed.');
});
Remember to handle any errors that may occur during the execution of these steps by using appropriate error handling techniques.