Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

ROLL NUMBER : 22BCE157

SUBJECT : FSWD
PRACTICAL – 8
Demonstrate Node.js using MySQL to perform the below operations: Create a database,
create a table, insert a record, and update the record.

1_CODE :
const { faker } = require('@faker-js/faker');

const mysql = require('mysql2');

const connection = mysql.createConnection({


host: 'localhost',
user: 'root',
database:'my_db',
password:'JUSTchill365'
});

connection.connect((err)=>{
if(err){
console.log("error connecting to mysql,err");
return;
}
console.log("connected to MySql server");

});

try {
const createDbQuery = "CREATE DATABASE IF NOT EXISTS my_db";

connection.query(createDbQuery,(err,results)=>{
if(err){
console.error("error creating database",err);
return;
}
console.log("database created successfully");
});
const createTableQuery = `
CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(25) NOT NULL,
email VARCHAR(50) NOT NULL
)
`;
connection.query(createTableQuery,(err,results)=>{
if(err) throw err;
console.log("user table created successfully : ",results);
});

const showTablesQuery = 'SHOW TABLES';


connection.query(showTablesQuery, (err, results) => {
if (err) throw err;
console.log('Tables in the database:',results);});

const insertQuery = `
INSERT INTO user (name, email) VALUES
('John Doe', 'johndoe@example.com'),
('Jane Smith', 'janesmith@example.com')
`;
connection.query(insertQuery, (err, results) => {
if (err) throw err;
console.log("Inserted 2 records into the user table:",results);});

connection.query('SELECT * FROM user', (err, results) => {


if (err) throw err;
console.log('User table contents:');
console.table(results);});

const updateQuery = `
UPDATE user SET email = 'newemail@example.com' WHERE id = 1
`;
connection.query(updateQuery, (err, results) => {
if (err) throw err;

console.log('Updated record in the user table: ',results);});

connection.query('SELECT * FROM user', (err, results) => {


if (err) throw err;
console.log('User table contents:');
console.table(results);});

} catch (error) {
console.log(error);
}

connection.end();

1_OUTPUT :

You might also like