FSPR9
FSPR9
Demonstrate Node.js using MySQL to perform the below operations using the user-
defined function: delete record, select record, select unique, drop table.
Step-1. Install Node.js
Step-2. Verify that Node.js was properly installed with the following
Command in CMD: node --version
Step-3. Verify whether NPM (Node Package Manager) is installed or not with the following
command in CMD: npm --version
1. Start XAMPP: Open the XAMPP control panel and start the Apache and MySQL services
if they are not already running.
2. Access phpMyAdmin: Open your web browser and go to http://localhost/phpmyadmin/.
This will open phpMyAdmin, a web-based MySQL administration tool that is included
with XAMPP.
Step-5. Create a new folder for your project: Open Visual Studio Code and create a new
folder where you want to store your project files.
Step-6. Open Terminal in Visual Studio Code: Once you have your folder open in Visual
Studio Code, open the integrated terminal. You can do this by selecting Terminal > New
Terminal from the menu bar.
Step-7. Initialize a new Node.js project: In the terminal, navigate to your project folder and
run the following command to initialize a new Node.js project:
npm init -y
Step-8. Install the MySQL package: Install the mysql package using npm by running the
following command in the terminal:
npm install mysql
Step-9. Create a new JavaScript file: Create a new file app.js. This file will contain your
Node.js code.
File name: app.js
// Delete record
const deleteRecord = (id) => {
const query = `DELETE FROM my_table WHERE id = ?`;
connection.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting record: ' + err.stack);
return;
}
console.log('Record deleted successfully.');
});
};
// Select record
const selectRecord = (id) => {
const query = `SELECT * FROM my_table WHERE id = ?`;
connection.query(query, [id], (err, results) => {
if (err) {
console.error('Error selecting record: ' + err.stack);
return;
}
console.log('Selected record:', results[0]);
});
};
// Drop table
const dropTable = () => {
//create my_table first under my_database first
const query = `DROP TABLE my_table1`;
connection.query(query, (err, results) => {
if (err) {
console.error('Error dropping table: ' + err.stack);
return;
}
console.log('Table dropped successfully.');
});
};
// Delete a record
deleteRecord(1);
// Select a record
selectRecord(1);
// Drop table
dropTable();
Step-10. Modify the MySQL connection details: Modify the MySQL connection details in the
code to match your MySQL server configuration. Update the host, user, password, and
database properties in the createConnection function call.
Step-11. Run the script: Save your app.js file and return to the terminal in Visual Studio
Code. Run the script by executing the following command:
node app.js
Step-12. Verify the output: Check the output in the terminal to see if the script executed
successfully.