Skip to content
| Marketplace
Sign in
Visual Studio Code>Other>mysql connector for nodejsNew to Visual Studio Code? Get it now.
mysql connector for nodejs

mysql connector for nodejs

Abdul Kalam

|
758 installs
| (0) | Free
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

Feature -1

set up REPL

1)node 2)For array odd and even const array=[1,2,3,4,5,6,7,8,9,10] const evenNumbers=array.filter((i)={return i%2==0}); const oddNumbers=array.filter((i)={return i%2!=0});

oddNumbers()

Feature-2 a) Using built in fs modules to do basic file operations Code: const fs=require('fs');

//Read the file const data=fs.readFileSync('hello.txt','utf-8');

console.log("Data inside file is : " , data);

//Write into the file fs.writeFileSync('hello.txt','This will overwrite the file');

console.log("Data after writing the file : ", fs.readFileSync('hello.txt','utf-8'));

//Append the file fs.appendFileSync('hello.txt',' \n This is appended text.',()=*{ console.log("data append successfully")} );

console.log('file after appending new text : ',fs.readFileSync('hello.txt','utf-8'));

//Rename the file fs.rename('hello.txt','hello2.txt',()=*{});

//Delete the file fs.unlink('hello2.txt',()=*{});

c) Creating a user module to convert currencies. Code: coverterModule.js //Module Code const exchangeRates = { USD: { INR: 84.0, EUR: 0.94, GBP: 0.81, }, INR: { USD: 0.012, EUR: 0.011, GBP: 0.0098, }, EUR: { USD: 1.06, INR: 89.0, GBP: 0.86, }, GBP: { USD: 1.24, INR: 109.76, EUR: 1.17, }, };

const convertCurrency=(amount,from,to)={ const fromCurrency=from.toUpperCase(); const toCurrency=to.toUpperCase(); console.log(fromCurrency,toCurrency) if(exchangeRates[fromCurrency] && exchangeRates[fromCurrency][toCurrency]){ const conversionRate=exchangeRates[fromCurrency][toCurrency]; const converted=amountconversionRate;

    return converted.toFixed(2);
}
else{
    throw new Error(`conversion rate from ${from} to ${to} is not found.`)
}
 

}

module.exports={convertCurrency}

converter.js //Main code const {convertCurrency}=require('./currencyConverter');

const amountInINR=convertCurrency(100,'USD','INR');

console.log(100 USD is equal to ${amountInINR} INR);

const EURInINR=convertCurrency(100,'EUR','INR');

console.log(100 EUR is equal to ${EURInINR} INR);

const INRInGBP=convertCurrency(100,'INR','GBP');

console.log(100 INR is equal to ${INRInGBP} GBP);

b) Program using third party modules using npm Code: const express = require ('express');

const app=express();

const port=3000;

app.get('/',(req,res)=*{ res.send("Hello World "); })

app.listen(port,()=*{ console.log(App listening to port ${port}); })

d) Using the path module Code : const path = require('path');

const filePath = 'C:/Users/HP/Documents/WT Assigments/Excercise-2/path.js';

const baseName = path.basename(filePath); console.log('Base Name:', baseName);

const dirName = path.dirname(filePath); console.log('Directory Name:', dirName);

const joinedPath = path.join(baseName, 'user', 'docs', 'newfile.txt'); console.log('Joined Path:', joinedPath);

const extName = path.extname(filePath); console.log('Extension Name:', extName);

const isAbs = path.isAbsolute(filePath); console.log('Is Absolute Path:', isAbs);

e) Program using fs module to perform non-blocking I/O Code: const fs=require('fs')

fs.readFile('hello2.txt','utf-8',(err,data)=*{ if(err){ console.log("Error while reading file . \n"+err) }

console.log("File content" + data)

})

//called before I/O operation console.log("This will display before content")

f) Using built in http module to serve different file types xampp

const http = require('http')

const server = http.createServer((request, response) =* { response.statusCode = 200; response.setHeader('Content-Type', 'text/html') response.write(*html* *head* *link rel="stylesheet" href="login.css"* *head* *body* *div class="login-page"* *div class="form"* *form class="register-form"* *input type="text" placeholder="name"/* *input type="password" placeholder="password"/* *input type="text" placeholder="email address"/* *button*create*button* *p class="message"*Already registered? *a href="#"*Sign In*a**p* *form* *form class="login-form"* *input type="text" placeholder="username"/* *input type="password" placeholder="password"/* *button*login*button* *p class="message"*Not registered? *a href="#"*Create an account*a**p* *form* *div* *div* *body* *html*) response.end() })

const hostname = 'localhost' const port = 5001

server.listen(port, hostname, () =* { console.log(Server runnning at ${port}) })

//for pdf server.pdf const http=require('http') const fs=require('fs') const path=require('path')

const hostname='localhost' const port=6969

const server=http.createServer((req,res)={ if(req.url==='/pdf'){ const filepath=path.join(__dirname,'ilove.pdf') fs.readFile(filepath,(err,content)={ if(err){ res.writeHead(500,{'content-Type':'text/plain'}) res.end('Server Error') } else{ res.writeHead(200,{'content-Type':'application/pdf'}) res.end(content) } }) } else{ res.writeHead(500,{'content-Type':'text/plain'}) res.end('Bhagg Jaa D.K Bose') } })

server.listen(port, hostname, () =* { console.log(Server runnning at ${port}) })

videofile.js const http=require('http') const fs=require('fs') const path=require('path')

const hostname='localhost' const port=6971

const server=http.createServer((req,res)={ if(req.url==='/video'){ const filepath=path.join(__dirname,'jethalal.mp4') fs.readFile(filepath,(err,content)={ if(err){ res.writeHead(500,{'Content-Type':'text/plain'}) res.end('Server Error') } else{ res.writeHead(200,{'Content-Type':'video/mp4'}) res.end(content) } }) } else{ res.writeHead(500,{'Content-Type':'text/plain'}) res.end('Bhagg Jaa D.K Bose') } })

server.listen(port, hostname, () =* { console.log(Server runnning at ${port}) })

Feature-3

open xammp create db and table

insert/update/select/delete operation in one file const mysql=require('mysql2');

//create a connection to the database

const conn=mysql.createConnection({ host:'localhost', user:'root', password:'', database:'db_name' })

conn.connect((err)=*{

if(err){ 

    console.log("Error while connecting the database \n " ,err); 

    return ; 

} 

console.log('connected to Database Successfully'); 

})

const p1=[{Pid:6,Pname:'fridge',Pcat:'Electricals',Price:20000,Pstock:10}, {Pid:5,Pname:'TV',Pcat:'Electricals',Price:25000,Pstock:15}];

//Insert query

conn.query("insert into product SET ?",p1,(err,res)=*{

if(err){ 

    console.log("Error while query the database \n " ,err); 

    return ; 

} 

console.log('Inserted Data successfully .')

})

conn.query("SELECT * FROM product",(err,res)=*{ if(err){ console.log("Error while query the database ",err); return ; } console.log(res); })

conn.query("DELETE FROM product WHERE Pid=?",4,(err,res)=*{ if(err){ console.log("error"); return; }

  console.log(res);

})

//updating table

conn.query('update product set price = ? where pid= ?',[50000,3],(err,results)=*{ if(err){ console.log("error updating table") } console.log('Updated the table '); }) conn.end();

Feature-4

a) Create a Node.js script that emits an event only if an element in an array is even, and handle that event with a listener. const EventEmitter=require("events") const emitter=new EventEmitter()

const number=[1,2,3,4,5,6]; emitter.on('evenNumber',(number)=*{ console.log(Even number found: ${number}) })

number.forEach((number)=* { if(number%2===0){ emitter.emit('evenNumber',number) } });

b) Create a Node.js script that emits an event when the temperature exceeds a certain threshold and handle that event. const EventEmitter=require("events") const emitter=new EventEmitter()

const temperatureThreshold = 30; const temperatures = [25, 28, 31, 29, 35];

emitter.on('highTemperature', (temp) =* { console.log(High temperature detected: ${temp}°C); });

temperatures.forEach((temp) =* { if (temp * temperatureThreshold) { emitter.emit('highTemperature', temp); } });

c) A simple chat application that emits events when a user joins and sends messages.

const event=require("events")

const emitter=new event();

let users={} emitter.on('joined',(username)=*{ users[username]=[] console.log(${username} joins the chat)

})

emitter.on('message',(username,message)=*{ if(!users[username]){ console.log(${username} does not exist. Please join) return } users[username].push(message) console.log(${username} has sent:${message}) })

emitter.emit('joined','Chana') emitter.emit('message','Chana','Boht Shana h')

emitter.emit('joined','Emiway') emitter.emit('message','Emiway','MACHAYENGE')

emitter.emit('message','Drake','Not Like Us')

d) Node js Script to resend OTP after 10 sec use timers and events/countdown timer

let counterdown=10 const timerid=setInterval(()={ if(counterdown0){ console.log(Resending OTP in ${counterdown} seconds) counterdown-- } else{ clearInterval(timerid) console.log("Resent OTP")

}

},1000)

e) Create a Node.js script that emits an event on file upload progress. Include the concept of timers.

const event = require('events');

const emitter = new event(); const totalSize = 100;

emitter.on('progress', (uploaded) =* { console.log(Uploaded ${uploaded}/${totalSize} MB); if (uploaded === totalSize) { console.log('Upload complete!'); } });

let uploaded = 0; const interval = setInterval(() =* { uploaded += 10; emitter.emit('progress', uploaded);

if (uploaded *= totalSize) {
    clearInterval(interval); 
}

}, 1000);

Feature-5(REACT start)

for create app:npx create-react-app appname if npx does not work use npm i create-react-app npm create-react-app appname

  1. A React application to create a component and export it. create this file in src folder

Header.js

import React from 'react'

const Header = (props) =* {

return (

*div* 

*h1*HELLOOOOOOOOOOOOOOOO BACHOOOOOOOOOOOOOOOOO FROM HEADER COMPONENT*h1* 

*h2* 

    Hello {props.name} 

*h2* 

*div* 

)

}

export default Header

APP.js

import react from 'react'

import Header from './components/Header'

function Greeting(){

return(

*h1*Hello BKLODO from GREETING COMPONENT*h1* 

)

}

function App(){

return(

*div* 

  *Header name="SIES"/* 

  *Greeting/* 

      *div* 

)

}

export default App

  1. A react application to create a calculator as a functional component using props. const Calculator=(props)=*{

const add=()=*{

return props.n1+props.n2

}

const sub=()=*{

return props.n1-props.n2

}

const pro=()=*{

return props.n1*props.n2

}

const div=()=*{

return props.n1/props.n2

}

return(

div

pAddition : {add()}p

pSubtraction  : {sub()}p

pMultiplication  : {pro()}p

pDivision  : {div()}p

div

)

}

App.js all other will be same Calculator n1={10} n2={20}/

3)A react application to create a product page using functional component and props

product.js

import React from 'react'

import './Product.css'

import pop from '../vimbar.jpg'

export function Product(props){

return(

*div className='product'*a href={props.link}

    image tag

img src={"props.u"} alt='VIM BAR' height={100} width={150} * img

a

h4**h4

p**p

h4 className="product-title"{props.name}h4

p className="product-description"{props.desc}p

h4 className="product-price"{props.price}h4

div

)

}

app.js in App(){ div className="App"

h1PRODUCTSh1

*div className='products' *

*Product

link="redirect link"

image={imagelink}

name="Ghadi"

desc="Pehle istemal kare, fir Vishwas kare"

price="$5"

/*

div

div }

  1. A React Counter Application that allows users to track how many times they have clicked a button using useState hook.

import React from "react";

import { useState } from "react";

function UseStateHook(){

const [count,setCounter]=useState(0)

const increment=()=*{

setCounter(count+1)

}

return (

div

h1Program using hooks useState: Counter apph1

h1You clicked {count} times h1

button onClick={increment}incrementbutton

br/

div

)

}

include this in app.js

  1. A React Application using useState hook to increment/decrement/reset a state. import { useState } from "react";

export const Counter=()=*{

const[count,setCount]=useState(0);

const handleIncrease=() =*{

setCount(count+1);

};

const handleReset=() =*{

setCount(0);

};

const handleDecrease=() =*{

setCount(count-1);

};

return(

div className="counter"

h1Counter Apph1

button onClick={handleIncrease}INCREASEbutton

br/

*p *Count:{count}p

br/

button onClick={handleDecrease}Decreasebutton**br/

button onClick={handleReset}RESETbutton

div

)

}

  1. A React Application using useEffect hook to display a congratulatory message on title bar when click count reaches 5. alert.js import React,{useState,useEffect} from "react";

export const Alert=()=*{

const [count,setCount]=useState(0);

useEffect(()=*{ if(count===5){ document.title="CONGRATULATIONS AND CELEBRATION🎉✨🧨" } else{ document.title=Click Count :${count} }

},[count])

return(

div

h1**h1

pClick Countp

*button onClick={()=setCount(count+1)}Click Mebutton

div ) }

7)A React Application using useEffect hook to display Employee Information as entered in the Form

import React, { useState, useEffect } from 'react';

const EmployeeForm = () =* {

const [employee, setEmployee] = useState({ name: '', position: '', department: '' });

const [submittedEmployee, setSubmittedEmployee] = useState(null);

const handleChange = (e) =* {

const { name, value } = e.target;

setEmployee((prevEmployee) =* ({

...prevEmployee,

[name]: value,

}));

};

const handleSubmit = (e) =* {

e.preventDefault();

setSubmittedEmployee(employee);

};

useEffect(() =* {

if (submittedEmployee) {

console.log('Employee submitted:', submittedEmployee);

}

}, [submittedEmployee]);

return (

div

form onSubmit={handleSubmit}

labelName:label

input type="text" name="name" value={employee.name} onChange={handleChange} /brbr

labelPosition:label

input type="text" name="position" value={employee.position} onChange={handleChange} /brbr

labelDepartment:label

input type="text" name="department" value={employee.department} onChange={handleChange} /brbr

button type="submit"Submitbutton

form

{submittedEmployee && (

div

h2Employee Informationh2

pName: {submittedEmployee.name}p**br/

pPosition: {submittedEmployee.position}p**br/

pDepartment: {submittedEmployee.department}p**br/

div

)}

div

);

};

export default EmployeeForm;

Feature 6 1)A react application to create a class component that increment/decrement a counter

Counter.js:

import React from "react";

import './Counter.css'

export class Counter extends React.Component{

constructor(props){

super(props);

this.state={

count:props.start

}

}

increment=()=*{

this.setState({count:this.state.count+1});

}

decrement=()=*{

this.setState({count:this.state.count-1});

}

render(){

return(

div

h1Counter :{this.state.count}h1

button className="btn" onClick={this.increment}Incrementbutton

button className="btn" onClick={this.decrement}Decrementbutton

div

)

} }

App.js:

import { Counter } from "./class/Counter";

import './App.css'

import { Greeting } from "./class/Greeting";

import React from 'react'

class App extends React.Component{

render(){

return div className="App"

Greeting name="Lokesh"/

Counter start={10}/

div

};

}

export default App

  1. A react Application to count the number of characters in a user-input message.

Counter.js:

import React from "react";

import './Counter.css'

export class Counter extends React.Component{

constructor(props){

super(props);

this.state={

count:props.start,

text: ""

}

}

increment=()=*{

this.setState({count:this.state.count+1});

}

decrement=()=*{

this.setState({count:this.state.count-1});

}

handleOnChange=(event)=*{

this.setState({text:event.target.value})

}

render(){

const textareaStyle = {

width: '30%',

height: '100px',

padding: '10px',

fontSize: '16px',

borderRadius: '5px',

border: '1px solid #ccc'

};

return(

div

h1Counter :{this.state.count}h1

button className="btn" onClick={this.increment}Incrementbutton

*button className="btn" onClick={this.decrement}Decrementbutton**br/*br/

*textarea style={textareaStyle} className="form-control" onChange={this.handleOnChange}*textarea

p{this.state.text.length} CHARACTERSp

div

)

}

}

3)A React App to demonstrate Life Cycle of React.

Applifecycle.js

import React, { useState } from 'react';

import '../App.css'; // Assuming you have some styles here

import ComponentA from './ComponentA';

import ComponentB from './ComponentB';

const AppLifecycle = () =* {

const [showComponentA, setShowComponentA] = useState(true);

const toggleComponent = () =* {

const currentValue = showComponentA; // Store current value

setShowComponentA(!currentValue); //toggle

};

return (

div className="AppLifecycle"

h1App Lifecycle h1

button onClick={toggleComponent}

{showComponentA ? 'Show Component B' : 'Show Component A'}

button

{showComponentA ? ComponentA / : ComponentB /}

div

);

};

ComponentA.js

// ComponentA.js

import React from 'react';

class ComponentA extends React.Component {

constructor(props) {

super(props);

console.log('Component A: Constructor');

}

componentDidMount() {

console.log('Component A: componentDidMount');

}

componentDidUpdate() {

console.log('Component A: componentDidUpdate');

}

componentWillUnmount() {

console.log('Component A: componentWillUnmount');

}

render() {

console.log('render: Rendering the component A');

return h3This is Component Ah3;

}

}

export default ComponentA;

ComponentB.js:

// ComponentB.js

import React from 'react';

class ComponentB extends React.Component {

constructor(props) {

super(props);

console.log('Component B: Constructor');

}

componentDidMount() {

console.log('Component B: componentDidMount');

}

componentDidUpdate() {

console.log('Component B: componentDidUpdate');

}

componentWillUnmount() {

console.log('Component B: componentWillUnmount');

}

render() {

console.log('render: Rendering the componentB');

return h3This is Component Bh3;

}

}

export default ComponentB;

4)A React Form App to display user Preferences (use Controlled and Uncontrolled components)

import React, { useState } from "react";

const FormsDemo=()=*{

const [inputvalues,setInputValues]=useState({

name:"",

course:"MCA",

lang:""

})

const handleChangeInput=(e)=*{

setInputValues({...inputvalues,[e.target.name]:e.target.value})

}

const handleSubmit=(e)=*{

e.preventDefault()

alert(`

name : ${inputvalues.name}\n

course:${inputvalues.course}\n

language : ${inputvalues.lang}

`)

}

return (

**

h6A React Form App to display user Preferences (controlled form)h6

form onSubmit={handleSubmit}

labelName :label

*input type="text" value={inputvalues.name} name="name" onChange={(e)=handleChangeInput(e)} /

br/

labelCourse : label

*select onChange={(e)=*handleChangeInput(e)} name="course" *

option value={"MCA"}MCAoption

option value={"MMS"}MMSoption

option value={"PGDM"}PGDMoption

select

br/

labelchoose language :  label**br/

*label htmlFor='english'*English label

*input type="radio" id="english" name="lang"  value={"english"}  onChange={(e)=handleChangeInput(e)}/

label htmlFor='spanish'Spanishlabel

*input type="radio" id="spanish" name="lang" value={"spanish"} onChange={(e)=*handleChangeInput(e)}/*br/

*button type="submit"*submit button

form

**

)

}

export default FormsDemo;

Uncontrolled form :

import React, { useRef, useState } from "react";

const FormsDemo1=()=*{

const nameRef=useRef(null);

const courseRef=useRef(null)

const langRef=useRef([])

const handleSubmit=(e)=*{

e.preventDefault()

alert(`

name : ${nameRef.current.value}\n

course:${courseRef.current.value}\n

language : ${getSelectedValue()} \n

`)

}

const getSelectedValue=()=*{

const selectradio=langRef.current.find(radio=* radio.checked)

if(selectradio){

return selectradio.value

}

}

return (

*form onSubmit={(e)=handleSubmit(e)}

labelName :label

input type="text" ref={nameRef} name="name" /

br/

labelCourse : label

*select name="course" ref={courseRef} *

option value={"MCA"}MCAoption

option value={"MMS"}MMSoption

option value={"PGDM"}PGDMoption

select

br/

labelchoose language :  label**br/

*label htmlFor='english'*English label

input type="radio" id="english" name="lang"  value={"english"} ref={el = langRef.current[0] = el}/*

label htmlFor='spanish'Spanishlabel

input type="radio" id="spanish" name="lang"  value={"spanish"} ref={el = langRef.current[1] = el}/*br/

*button type="submit"*submit button

form

)

}

export default FormsDemo1

  1. Newsletter subscription form in React with validations

import React, { useState } from "react";

export default function ValidationForm() {

const [formData, setFormData] = useState({ fname: '', lname: '', email: '' });

const [error, setError] = useState({ fname: '', lname: '' });

const [buttonDisable, setDisable] = useState(true);

const handleChange = (event) =* {

const { name, value } = event.target;

setFormData({ ...formData, [name]: value });

if (name === 'fname' || name === 'lname') {

if (value.length * 5) {

setError({ ...error, [name]: 'Must have at least 5 characters' });

} else {

setError({ ...error, [name]: '' });

}

}

setDisable(!formData.fname || !formData.lname || error.fname || error.lname);

};

const handleSubmit = (event) =* {

event.preventDefault();

alert(FName: ${formData.fname} \nLName: ${formData.lname} \nEmail: ${formData.email});

};

return (

form onSubmit={handleSubmit}

p

label

First Name:

input type="text" name="fname" value={formData.fname} onChange={handleChange} /

label

p

{error.fname && div style={{ color: 'red' }}{error.fname}div}

p

label

Last Name:

input type="text" name="lname" value={formData.lname} onChange={handleChange} /

label

p

{error.lname && div style={{ color: 'red' }}{error.lname}div}

p

label

Email:

input type="email" name="email" value={formData.email} onChange={handleChange} /

label

p

button type="submit" disabled={buttonDisable}Submitbutton

form

);

}

6.A React app to perform routing (SPA)

Home.js

import React from 'react'

const Home = () =* {

return (

div

h1 Home h1

div

)

}

export default Home

Contact.js

import React from 'react'

const Contact = () =* {

return (

div

h1Contact Ush1

div

)

}

export default Contact

Aboutus.js

import React from 'react'

export const Aboutus = () =* {

return (

div

h1About Ush1

div

)

}

App.js:

import React from 'react'

import {BrowserRouter, Link, Route, Routes} from 'react-router-dom'

import Home from './components/Home'

import { Aboutus } from './components/Aboutus'

import Contact from './components/Contact'

import ControlForm from './forms/ControlForm';

import { Counter } from './class/Counter'

import { Product } from './components/Product'

function App ()  {

return (

BrowserRouter

nav class="navbar navbar-expand-lg navbar-light bg-light"

a class="navbar-brand" href="#"Navbara

button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"

*span class="navbar-toggler-icon"*span

button

div class="collapse navbar-collapse" id="navbarNav"

ul class="navbar-nav me-auto mb-2 mb-lg-0 gap-2"

li class="nav-item active"

*a class="nav-link" href="/home"*Home span class="sr-only"(current)span**a

li

li class="nav-item"

a class="nav-link" href="/counter"Countera

li

li class="nav-item"

a class="nav-link" href="/product"Productsa

li

li class="nav-item"

a class="nav-link" href="/controlform"Control Forma

li

li class="nav-item"

a class="nav-link" href="/contact"Contact Usa

li

li class="nav-item"

a class="nav-link" href="/aboutus"About Usa

li

ul

div

nav

div

Routes

Route path='/home' element={Home/}/

Route path='/aboutus' element={Aboutus/}/

Route path='/contact' element={Contact/}/

Route path='/counter' element={Counter start={10}/}/

Route path='/product' element={Product/}/

Route path='/controlform' element={ControlForm /}/

Routes

div

BrowserRouter

)

}

export default App

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2025 Microsoft