NodeJS Slip 5B solution

Step 1:

First, install the mysql library by running:

npm install mysql

Step 2:

Now, create a Node.js file, let's name it databaseOperations.js:

// databaseOperations.js:
const mysql = require('mysql');

// Create a connection to the MySQL database
const connection = mysql.createConnection({
host: 'your_database_host',
user: 'your_database_user',
password: 'your_database_password',
database: 'your_database_name'
});

// Connect to the database
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
return;
}
console.log('Connected to the database');

// Select all records from the "Customers" table
connection.query('SELECT * FROM Customers', (selectErr, results) => {
if (selectErr) {
console.error('Error selecting records:', selectErr);
connection.end();
return;
}

// Display all records
console.log('All records from "Customers" table:', results);

// Specify the record you want to delete (replace 'your_criteria' with your actual criteria)
const recordToDelete = 'your_criteria';

// Delete the specified record
connection.query('DELETE FROM Customers WHERE your_column = ?', [recordToDelete], (deleteErr, deleteResult) => {
if (deleteErr) {
console.error('Error deleting record:', deleteErr);
connection.end();
return;
}

// Display success message
console.log('Record deleted successfully:', deleteResult);

// Close the database connection
connection.end();
});
});
});

No comments:

Post a Comment