0% found this document useful (0 votes)
11 views32 pages

Nodejslab 2

The document outlines the development of various applications including a Java standalone application for CRUD operations on a MySQL database, an XML validation example, a custom HTTP server using Node.js, an Express web application for student data management, and a React TODO application. Each section includes code snippets and instructions for implementation, demonstrating the use of different programming languages and technologies. The document serves as a comprehensive guide for building and validating applications across multiple platforms.

Uploaded by

trustworthy2055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views32 pages

Nodejslab 2

The document outlines the development of various applications including a Java standalone application for CRUD operations on a MySQL database, an XML validation example, a custom HTTP server using Node.js, an Express web application for student data management, and a React TODO application. Each section includes code snippets and instructions for implementation, demonstrating the use of different programming languages and technologies. The document serves as a comprehensive guide for building and validating applications across multiple platforms.

Uploaded by

trustworthy2055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Aim:

☛ Develop a java stand alone application that connects with the database (Oracle / mySql) and
perform the CRUD operation on the database tables.

Solution :

I will provide you with the MySQL code for creating the student table and make some changes to
your Java code to improve it:

☛ MySQL Code:

sql> CREATE TABLE IF NOT EXISTS student (

s_id INT PRIMARY KEY,

s_nameVARCHAR(255),

s_addressVARCHAR(255)

);

This SQL code creates a table with three columns: s_id for student ID (primary key), s_name for
student name, and s_address for student address.

Java Code

[Link]

import [Link].*;

import [Link];

public class InsertData {

public static void main(String[] args) {

try (Connection con = [Link]("jdbc:mysql://localhost/mydb", "root", "");

Statements = [Link]()) {

Scanner sc = new Scanner([Link]);

[Link]("Inserting Data into student table:");

[Link]("________________________________________");
[Link]("Enter student id: ");

int sid = [Link]();

[Link]("Enter student name: ");

String sname = [Link]();

[Link]("Enter student address: ");

String saddr = [Link]();

String insertQuery = "INSERT INTO student VALUES(" + sid + ",'" + sname + "','" + saddr + "')";

[Link](insertQuery);

[Link]("Data inserted successfully into student table");

} catch (SQLException err) {

[Link]("ERROR: " + err);

Output :

Inserting Data into student table:

________________________________________

Enter student id: 101

Enter student name: John Doe

Enter student address: 123 Main Street

Data inserted successfully into student table

[Link]

import [Link].*;
import [Link];

public class UpdateData {

public static void main(String[] args) {

try (Connection con = [Link]("jdbc:mysql://localhost/mydb", "root", "");

Statements = [Link]()) {

Scanner sc = new Scanner([Link]);

[Link]("Update Data in student table:");

[Link]("________________________________________");

[Link]("Enter student id: ");

int sid = [Link]();

[Link]("Enter student name: ");

String sname = [Link]();

[Link]("Enter student address: ");

String saddr = [Link]();

String updateQuery = "UPDATE student SET s_name='" + sname + "', s_address='" + saddr + "'
WHERE s_id=" + sid;

[Link](updateQuery);

[Link]("Data updated successfully");

} catch (SQLException err) {

[Link]("ERROR: " + err);

}
Output :

Update Data in student table:

________________________________________

Enter student id: 101

Enter student name: Jane Doe

Enter student address: 456 Broad Street

Data updated successfully

[Link]

import [Link].*;

import [Link];

public class DeleteData {

public static void main(String[] args) {

try (Connection con = [Link]("jdbc:mysql://localhost/mydb", "root", "");

Statements = [Link]()) {

Scanner sc = new Scanner([Link]);

[Link]("Delete Data from student table:");

[Link]("________________________________________");

[Link]("Enter student id: ");

int sid = [Link]();

String deleteQuery = "DELETE FROM student WHERE s_id=" + sid;

[Link](deleteQuery);

[Link]("Data deleted successfully");


} catch (SQLException err) {

[Link]("ERROR: " + err);

Output :

Delete Data from student table:

______________________________________

Enter student id: 101

Data deleted successfully

[Link]

import [Link].*;

public class DisplayData {

public static void main(String[] args) {

try (Connection con = [Link]("jdbc:mysql://localhost/mydb", "root", "");

Statement s = [Link]()) {

ResultSet rs = [Link]("SELECT * FROM student");

if (rs != null) {

[Link]("SID \t STU_NAME \t ADDRESS");

[Link]("________________________________________");

while ([Link]()) {

[Link]([Link]("s_id") + " \t " + [Link]("s_name") + " \t " +


[Link]("s_address"));

[Link]("________________________________________");

}
}

} catch (SQLException err) {

[Link]("ERROR: " + err);

Output :

SID STU_NAME ADDRESS

________________________________________

102 Alice Smith 789 Oak Avenue

________________________________________

103 Bob Johnson 567 Pine Road

Aim:

☛ Create an xml for the bookstore. Validate the same using both DTD and XSD.

Solution :

☛ XML data to validate:

[Link]

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE bookstore[

<!ELEMENT bookstore (book+)>

<!ELEMENT book (title, author, price)>

<!ELEMENT title (#PCDATA)>

<!ELEMENT author (#PCDATA)>

<!ELEMENT price (#PCDATA)>

]>

<bookstore>
<book>

<title>Introduction to XML</title>

<author>John Doe</author>

<price>29.99</price>

</book>

<book>

<title>Programming with XML</title>

<author>Jane Smith</author>

<price>39.99</price>

</book>

</bookstore>

☛ XML schema (XSD) data:

[Link]

<?xml version="1.0" encoding="UTF-8"?>

<xs:schema xmlns:xs="[Link]

targetNamespace="[Link]

xmlns="[Link]

<xs:element name="root">

<xs:complexType>

<xs:sequence>

<xs:element name="bookstore" type="bookstoreType"/>

</xs:sequence>

</xs:complexType>

</xs:element>

<xs:complexType name="bookstoreType">

<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="0" maxOccurs="unbounded"/>

</xs:sequence>

</xs:complexType>

<xs:complexType name="bookType">

<xs:sequence>

<xs:element name="title" type="xs:string"/>

<xs:element name="author" type="xs:string"/>

<xs:element name="price" type="xs:decimal"/>

</xs:sequence>

</xs:complexType>

</xs:schema>

To Check the Validity :

1. Go to the below link,


[Link]

2. Place the XML code in the XML Validate.

3. Place the XSD code in the XML Schema Data.

4. Then click the validate Button.

5. Then it will show the Document as Valid.

Output :
Aim:

☛ Create a custom server using http module and explore the other modules of Node JS like OS,
path, event.

Solution :

☛ Open Terminal or Command Prompt:

Open a terminal or command prompt in the directory where you saved your [Link] file.

☛ Run the Server Script:

Execute the server script using the [Link] runtime. In the terminal, run:

node [Link]

[Link] development course

This will start the HTTP server, and you should see the message "Server running at
[Link]

☛ Access the Server:

Open your web browser and navigate to [Link] or [Link] You should
see the response "Hello, World!".

☛ Check OS Information:

In the same terminal where your server is running, you'll see information about your operating
system (OS) type, platform, architecture, CPU cores, etc.

☛ Check Current Working Directory:

The current working directory of the script is printed in the terminal.

☛ Check Joined Path:


The joined path using the path module is printed in the terminal.

☛ Check Custom Event:

The script emits a custom event and listens for it. In the terminal, you should see the message
"Custom Event Triggered: { message: 'Hello from custom event!' }".

Ebook website platform

☛ Stop the Server:

To stop the server, press Ctrl+C in the terminal where the server is running.

[Link]

// Step 1: Import required modules

const http = require('http');

const os = require('os');

const path = require('path');

const { EventEmitter } = require('events');

// Step 2: Create an instance of EventEmitter

const eventEmitter = new EventEmitter();

// Step 3: Create a simple HTTP server

const server = [Link]((req, res) => {

[Link](200, { 'Content-Type':'text/plain' });

[Link]('Hello, World!\n');

});

// Step 4: Define server port and hostname

constport = 3000;

consthostname = '[Link]';

// Step 5: Listen for requests on the specified port and hostname

[Link](port, hostname, () => {

[Link]('Server running at [Link]


});

// Step 6: Print OS information

[Link]('OS Type:', [Link]());

[Link]('OS Platform:', [Link]());

[Link]('OS Architecture:', [Link]());

[Link]('CPU Cores:', [Link]().length);

// Step 7: Print current working directory

[Link]('Current Working Directory:', [Link]());

// Step 8: Join paths using the path module

const joinedPath = [Link](__dirname, 'public', 'images');

[Link]('Joined Path:', joinedPath);

// Step 9: Handle a custom event

[Link]('customEvent', (data) => {

[Link]('Custom Event Triggered:', data);

});

// Step 10: Emit a custom event

[Link]('customEvent', { message:'Hello from custom event!' });

Output :

In the Terminal:
In the Browser:

Link: [Link]

Aim:

☛ Develop an express web application that can interact with REST API to perform CRUD
operations on student data. (Use Postman)

Solution :

 Firstly we need to create a new folder and open the folder in the command prompt and
enter a command as below:

 npminit -y

 Open that folder in the vscode by entering code.

 Next in the terminal we need to install all the packages we need, so we mainly use express
and sqlite3.

 The Command to install express and sqlite3 is

 npm install express sqlite3


Then create file named as the [Link] and [Link]

[Link]

const sqlite3 = require('sqlite3').verbose();

// Function to initialize the database schema

function initializeDatabase() {

const db = new [Link]('./[Link]', (err) => {

if (err) {

[Link]([Link]);

} else {

[Link]('Connected to the SQLite database.');

createStudentsTable(db);

});

// Close the database connection when the Node process exits

[Link]('exit', () => {

[Link]((err) => {

if (err) {

[Link]([Link]);

} else {

[Link]('Disconnected from the SQLite database.');

});

});

// Function to create the 'students' table if it doesn't exist

function createStudentsTable(db) {

const createTableQuery = `

CREATE TABLE IF NOT EXISTS students (


id INTEGER PRIMARY KEY AUTOINCREMENT,

name TEXT,

age INTEGER,

grade TEXT

);

`;

[Link](createTableQuery, (err) => {

if (err) {

[Link]([Link]);

} else {

[Link]('The students table has been created or already exists.');

});

[Link] = { initializeDatabase };

when we execute both the [Link] then the database will be created that is [Link]

[Link]

const express = require('express');

const sqlite3 = require('sqlite3');

const{ initializeDatabase } = require('./db');

const app = express();

const port = 3000;

// Connect to SQLite database

const db = new [Link]('./[Link]', (err) => {


if (err) {

[Link]([Link]);

} else {

[Link]('Connected to the SQLite database.');

});

// Middleware to parse request body as JSON

[Link]([Link]());

[Link]('/', (req, res) => {

[Link]('Welcome to the Student');

});

// Get all Students

[Link]('/students', (req, res) => {

[Link]('SELECT * FROM students', [], (err, rows) => {

if (err) {

return [Link]([Link]);

[Link](rows);

});

});

// Get a single student by id

[Link]('/students/:id', (req, res) => {

const id = [Link];

[Link]('SELECT * FROM students WHERE id = ?', [id], (err, row) => {

if (err) {

return [Link]([Link]);

}
[Link](row);

});

});

// Create a new student

[Link]('/students', (req, res) => {

const{ name, age, grade } = [Link];

[Link]('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', [name, age, grade], function
(err) {

if (err) {

return [Link]([Link]);

[Link](201).json({ id:[Link] });

});

});

// Update a student

[Link]('/students/:id', (req, res) => {

const id = [Link];

const{ name, age, grade } = [Link];

[Link]('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?', [name, age, grade, id],
function (err) {

if (err) {

return [Link]([Link]);

[Link]({ updatedID:id });

});

});

// Delete a student

[Link]('/students/:id', (req, res) => {

const id = [Link];
[Link]('DELETE FROM students WHERE id = ?', id, function (err) {

if (err) {

return [Link]([Link]);

[Link]({ deletedID:id });

});

});

[Link](port, () => {

[Link]('Server running at [Link]

});

Output :

GET:

 Open Postman.

 Set the request type to GET.

 Enter the URL: [Link]


POST : Create a New Student

 Open Postman.

 Set the request type to POST.

 Enter the URL: [Link]

 Go to the "Body" tab.

 Select raw and set the body to JSON format.

GET: #all Students

 Set the request type to GET.

 Enter the URL: [Link]

 Click on the "Send" button

 You should receive a response with details of all students in your SQLite database.
DELETE:

 Set the request type to DELETE.

 Enter the URL for the student you want to delete (replace: id with an actual student
ID): [Link]

 Place instead of ID which replace with number that is ID to be deleted.

 Then click send


PUT:

 Set the request type to PUT.

 Enter the URL for the student you want to delete (replace: id with an actual student
ID): [Link]

 Go to the "Body" tab.

 Select raw and set the body to JSON format


Aim:

☛ Create a TODO application in react with necessary components and deploy it into github.

Solution :

Step 1: Set Up the Project

Our first task is to set up the React project. This step involves creating the necessary project
structure. Here's how you can do it:

1. Create a React App:

Open your terminal and navigate to your preferred directory. Run the following command to
generate a new React app. Replace "todo-app" with your desired project name:

npx create-react-app todo-app

This command will create a directory named "todo-app" with all the initial code required for a React
app.

2. Navigate to the Project Directory:

Change your working directory to the "todo-app" folder:

cd todo-app

3. Start the Development Server:

Launch the development server with the following command:

npm start

This will open your React app, and you�ll see the default React starter page in your web browser
at '[Link]

Website development services

Step 2: Create the App Component

In this step, we create the App component, which serves as the entry point to our Todo List
application.

import React from'react';

import TodoList from'./components/TodoList';


function App() {

return (

<div className="App">

<TodoList />

</div>

);

exportdefault App;

Step 3: Create the TodoList

src->Component

Now, let's create the 'TodoList' component, which is responsible for managing the list of tasks and
handling task-related functionality.

import React, { useState } from 'react';

import TodoItem from './TodoItem';

function TodoList() {

const [tasks, setTasks] = useState([

id: 1,

text: 'Doctor Appointment',

completed: true

},

id: 2,

text: 'Meeting at School',

completed: false

}
]);

const [text, setText] = useState('');

function addTask(text) {

const newTask = {

id: [Link](),

text,

completed: false

};

setTasks([tasks, newTask]);

setText('');

function deleteTask(id) {

setTasks([Link](task => [Link] !== id));

function toggleCompleted(id) {

setTasks([Link](task => {

if ([Link] === id) {

return {task, completed: ![Link]};

} else {

return task;

}));

return (

<div className="todo-list">

{[Link](task => (

<TodoItem

key={[Link]}

task={task}

deleteTask={deleteTask}
toggleCompleted={toggleCompleted}

/>

))}

<input

value={text}

onChange={e => setText([Link])}

/>

<button onClick={() => addTask(text)}>Add</button>

</div>

);

exportdefault TodoList;

Step 4: Create the place the TodoItem in

src->Component

In this step, we create the 'TodoItem' component, which represents an individual task in our Todo
List.

import React from'react';

function TodoItem({ task, deleteTask, toggleCompleted }) {

function handleChange() {

toggleCompleted([Link]);

return (

<div className="todo-item">

<input

type="checkbox"

checked={[Link]}

onChange={handleChange}
/>

<p>{[Link]}</p>

<button onClick={() => deleteTask([Link])}>

</button>

</div>

);

exportdefault TodoItem;

These three components, 'App', 'TodoList', and 'TodoItem', work together to create a functional Todo
List application in React. The 'TodoList' component manages the state of the tasks, and the
'TodoItem' component represents and handles individual tasks within the list.

Step 5: Styling

To enhance the visual appeal of your Todo List, you can apply some basic styling. Here�s an example
of how you can style the todo items. In the `[Link]` file, add the following styles:

.todo-item {

display: flex;

justify-content: space-between;

margin-bottom: 8px;

.todo-itemp {

color: #888;

text-decoration: line-through;

Your output should look like this:

Output :
Initially it looks like:

Next,

Aim:
☛ Create a service in react that fetches the weather information from open [Link] and
the display the current and historical weather information using graphical representation using
[Link]

Solution :

Step 1: Create an OpenWeatherMap Account and Generate API Key

 Visit the OpenWeatherMap website ([Link] and click on "Sign Up"


or "Log In" to create an account or log into your existing account.

 Once logged in, navigate to your account dashboard.

 From the dashboard, locate my API Keys section and click on "Create Key" or "API Keys" to
generate a new API key.

 Provide a name for your API key (e.g., "WeatherApp") and click on the "Generate" or
"Create" button.

 Your API key will be generated and displayed on the screen. Make sure to copy it as we will
need it later.

Locate API key

Step 2: Set up a new React project

 Open your terminal or command prompt.

 Run the following command to create a new React project:

npxcreate-react-app weather-app

 Once the project is created, navigate into the project directory:

cd weather-app

Step 3: Install required packages


In the project directory, install the necessary packages by executing the following command

npm install axios

We will use the Axios library to make HTTP requests to the OpenWeatherMap API.

Step 4: Create a Weather component

 Inside the "src" directory, create a new file called "[Link]" and open it in your code
editor.

 Add the following code to define a functional component named Weather:

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

import axios from 'axios';

const Weather = () => {

const [city, setCity] = useState('');

const [weatherData, setWeatherData] = useState(null);

const fetchData = async () => {

try {

const apiKey = 'c97c0c1086d42990e89d64d76f50bb61'; // Replace with your OpenWeatherMap


API key

const response = await [Link](

'[Link]

);

setWeatherData([Link]);

[Link]([Link]); //You can see all the weather data in console log

} catch (error) {

[Link](error);

};
useEffect(() => {

fetchData();

}, []);

const handleInputChange = (e) => {

setCity([Link]);

};

const handleSubmit = (e) => {

[Link]();

fetchData();

};

return (

<div>

<form onSubmit={handleSubmit}>

<input

type="text"

placeholder="Enter city name"

value={city}

onChange={handleInputChange}

/>

<button type="submit">Get Weather</button>

</form>

{weatherData ? (

<>

<h2>{[Link]}</h2>

<p>Temperature: {[Link]} C</p>

<p>Description: {[Link][0].description}</p>

<p>Feels like : {[Link].feels_like} C</p>

<p>Humidity : {[Link]}%</p>
<p>Pressure : {[Link]}</p>

<p>Wind Speed : {[Link]}m/s</p>

</>

):(

<p>Loading weather data...</p>

)}

</div>

);

};

export default Weather;

Replace {YOUR_API_KEY} in the API URL with the API key you generated from OpenWeatherMap.

Step 5: Connect the Weather component to your app.

 Open the "[Link]" file in the "src" directory.

 Replace the existing code with the following code:

import React from'react';

import Weather from'./Weather';

const App = () => {

return (

<div>

<h1>Weather Forecast App</h1>

<Weather />

</div>

);

};
exportdefault App;

Your output should look like this:

Output :

Initial Screen

After Supply the City name

You might also like