NodeJS Slip 1B solution

Step1:

you'll need to use the mysql package to interact with the MySQL database. First, make sure to install the mysql package using:
npm install mysql

Step2:

After installing the mysql package, you can create a Node.js file with the following code:

// Import the mysql package
const mysql = require('mysql');

// Create a connection to the MySQL server
const connection = mysql.createConnection({

host: 'localhost', // Change this to your MySQL server host
user: 'your_username', // Change this to your MySQL username
password: 'your_password', // Change this to your MySQL password
database: 'studentDB', // Database name

});

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

// SQL query to create the 'student' table
const createTableQuery = '
CREATE TABLE IF NOT EXISTS student (
Rno INT PRIMARY KEY,
Sname VARCHAR(255) NOT NULL,
Percentage FLOAT NOT NULL
); ';

// Execute the query to create the table
connection.query(createTableQuery, (queryErr, results) => {
if (queryErr) {
console.error('Error creating table:', queryErr.stack);
} else {
console.log('Student table created successfully');
}

// Close the MySQL connection
connection.end((endErr) => {
if (endErr) {
console.error('Error closing connection:', endErr.stack);
} else {
console.log('Connection closed');
}
});
});
});

No comments:

Post a Comment