Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

LAB on Internet Programming

Uploaded by

Sakshi Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

LAB on Internet Programming

Uploaded by

Sakshi Jadhav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

LAB on Internet Programming-2

Name: Saakshi Jadhav


Program: MCA Management (C)
PRN: 1062222772
Email: 1062222772@mitwpu.edu.in
Subject: Internet Programming 2 Lab
Faculty: Geeta Mete
Q-1.Ajax Using Get Request
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Ajax GET Demo</title>
<script>
function displayFullName() {
var request = new XMLHttpRequest();
request.open("GET", "greet.php?fname=Saakshi&lname=Jadhav");
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
request.send();
}
</script>
</head>
<body>
<div id="result">
<p>
Content of the result DIV box will be replaced by the server response
</p>
</div>
<button type="button" onclick="displayFullName()">Display Full Name</button>
</body>
</html>

Greet.php
<?php
if (isset($_GET["fname"]) && isset($_GET["lname"])) {
$fname = htmlspecialchars($_GET["fname"]);
$lname = htmlspecialchars($_GET["lname"]);
// Creating full name by joining first and last name
$fullname = $fname . " " . $lname;
// Displaying a welcome message
echo "Hello, $fullname!
Welcome to our website.";
} else {
echo "Hi there! Welcome to our website.";
}
?>

OUTPUT :
INITIAL PAGE :

AFTER CLICKING BUTTON :


Q-2.Ajax Using POST Request

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Javascript Ajax Post Demo</title>
<script>
function postComment() {
var request = new XMLHttpRequest();

request.open("POST", "conformation.php");

request.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
var myForm = document.getElementById("myForm");
var formData = new FormData(myForm);

request.send(formData);
}
</script>
</head>
<body>
<form id="myForm">
<label>Name:</label>
<div><input type="text" name="name" /></div>
<br />
<label>Comment:</label>
<div><textarea name="comment"></textarea></div>
<p><button type="button" onclick="postComment()">Post Comment</button></p>
</form>
<div id="result">
<p>
Content of the result DIV box will be replaced by the server response
</p>
</div>
</body>
</html>

Confirmation.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["name"]));
$comment = htmlspecialchars(trim($_POST["comment"]));
// Check if form fields values are empty
if (!empty($name) && !empty($comment)) {
echo "<p>Hi, <b>$name</b>. Your comment has been received successfully.<p>";
echo "<p>Here's the comment that you've entered: <b>$comment</b></p>";
} else {
echo "<p>Please fill all the fields in the form!</p>";
}
} else {
echo "<p>Something went wrong. Please try again.</p>";
}
?>

OUTPUT:
Q-3. JSON with JavaScript

<html>
<head>
<title>JSON example</title>
<script language="javascript">
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");
var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };
document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from
book
written by " + object2.author);
document.write("<hr />");
</script>
</head>
<body></body>
</html>

OUTPUT:
Q-4. JSON with PHP

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
string schemaJson = @"{ 'description': 'A person', 'type':
'object', 'properties': { 'name': {'type':'string'}, 'hobbies': { 'type':
'array', 'items': {'type':'string'} } } }"; JsonSchema schema =
JsonSchema.Parse(schemaJson); JObject person = JObject.Parse(@"{ 'name':
'James', 'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS'] }"); bool
valid = person.IsValid(schema); // true JSON with PHP
<?php
$arr = array('a' =>
1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

Q-5. JSON with Java

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class JSON_Example7_1 {
public static void main(String[] args) {
String s="{\"name\":\"geeta\",\"salary\":600000.0,\"age\":27}";
Object obj=JSONValue.parse(s);
JSONObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
double salary = (Double) jsonObject.get("salary");
long age = (Long) jsonObject.get("age");
System.out.println(name+" "+salary+" "+age);
}
}
Q-6. JSON with Ajax

<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function getWelcome() {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("GET", "data.json");
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
//the request is completed, now check its status
if (ajaxRequest.status == 200) {
document.getElementById("welcome").innerHTML =
ajaxRequest.responseText;
} else {
console.log("Status error: " + ajaxRequest.status);
}
} else {
console.log("Ignored readyState: " + ajaxRequest.readyState);
}
};
ajaxRequest.send();
}
</script>
</head>
<body>
<button type="button" onclick="getWelcome()">Okay</button>
<p id="welcome"></p>
</body>
</html>
Q-7. A student will not be allowed to sit in exam if his/her attendance is less
than 75%.Take following input from user
Number of classes held Number of classes attended.
And print percentage of class attended Is student is allowed to sit in exam or
not. Modify the above question to allow student to sit if he/she has medical
cause. Ask user if he/she has medical cause or not ('Y'or 'N' ) and print
accordingly. Write JavaScript code.

<html>
<script>
function checkExamEligibility(
classesHeld,
classesAttended,
hasMedicalCause
){
const attendancePercentage = (classesAttended / classesHeld) * 100;

if (hasMedicalCause === "Y") {


document.write(
"Due to medical cause, the student is allowed to sit in the exam."
);
} else if (attendancePercentage >= 75) {
document.write("The student is allowed to sit in the exam.");
} else {
document.write(
"The student's attendance percentage is ${attendancePercentage}%. Sorry, the
student is not allowed to sit in the exam."
);
}
}
const classesHeld = parseInt(prompt("Enter the number of classes held:"));
const classesAttended = parseInt(
prompt("Enter the number of classes attended:")
);
const hasMedicalCause = prompt(
"Does the student have a medical cause? (Y/N)"
);
checkExamEligibility(classesHeld, classesAttended, hasMedicalCause);
</script>
</html>
Output:

Q-8. Write JavaScript code that prompts the user to input a positive integer.
It should then print the multiplication table of that number.

<html>
<title>input Positive Number Multiplecation table</title>
<body>
<script type="text/javascript">
var num = parseInt(prompt("Enter an integer: "));
var range = parseInt(prompt("Enter a range: "));
for (let i = 1; i <= range; i++) {
var res = i * num;
document.write(num + " * " + i + " = " + res + "<br /> ");
}
</script>
</body>
</html>

Output:

Q-9. Write a program to Check Whether the Entered Year is Leap Year or not
(Hint: A leap year is one that is divisible by 400. Otherwise, a year that is
divisible by 4 but not by
100 is also a leap years. Other years are not leap years. For example, years
1912, 2000, and 1980 are leaps years, but 1835, 1999, and 1900 are not. )

<html>
<title>Leap Year</title>
<body>
<script type="text/javascript">
var year = parseInt(prompt('Enter an integer: '));

if ((0 == year % 4) && (0 != year % 100) || (0 == year % 400)) {


document.write(year + ' is a leap year');
} else {
document.write(year + ' is not a leap year');
}
</script>
</body>
</html>
OUTPUT:-

10. Write a JavaScript code using function without parameter and without returning
datatype type. Find the late charges applicable for not returning the book to the library on
time. Take input as fine per day and number of days. Total fine is the multiplication of fine
per day and number of days. Find the percentage of marks for 5 subjects. Take input as
marks for 5subjects and find the percentage.

<html>
<script>
function calculateLateCharges() {
const finePerDay = parseFloat(prompt("Enter the fine per day:"));
const numberOfDays = parseInt(prompt("Enter the number of days late:"));
const totalFine = finePerDay * numberOfDays;
document.write(
`Late charges for not returning the book on time: $${totalFine}`
);
}
function calculatePercentageOfMarks() {
let totalMarks = 0;

for (let i = 1; i <= 5; i++) {


const subjectMarks = parseFloat(
prompt(`Enter marks for subject ${i}:`)
);
totalMarks += subjectMarks;
}
const percentage = (totalMarks / 5).toFixed(2);
document.write(`Percentage of marks for 5 subjects: ${percentage}%`);
}
calculateLateCharges();
calculatePercentageOfMarks();
</script>
</html>

Output:
11. Write JavaScript code using function with parameter and with returning datatype to
implement the following operations. Find the total salary deducted. Take input as
number of days worked, number of leaves and pay per day. Find the total salary hike.Take
input as salary and percentage of raise received.

<!DOCTYPE html>
<html>
<head>
<title>Salary Deduction Calculator</title>
</head>
<body>
<p>
Find the total salary deducted. take input as number of days worked,
number of leaves and pay per day.
</p>

<script>
function calculateSalaryDeduction(daysWorked, leavesTaken, payPerDay) {
var totalSalary = daysWorked * payPerDay;
var deduction = leavesTaken * payPerDay;
var totalDeduction = totalSalary - deduction;
return totalDeduction;
}
var daysWorked = parseInt(prompt("Enter the number of days worked:"));
var leavesTaken = parseInt(prompt("Enter the number of leaves taken:"));
var payPerDay = parseFloat(prompt("Enter the pay per day:"));

var salaryDeduction = calculateSalaryDeduction(


daysWorked,
leavesTaken,
payPerDay
);
document.write(
"Total salary deducted: Rs. " + salaryDeduction.toFixed(2)
);
</script>
</body>
</html>

OUTPUT:-
12. Create a JavaScript form for Student Registration to capture student
name, phone number and email and perform validation using Regular
Expression.
<html>
<head>
<script>
function ValidateCode() {
var name = document.forms["RegForm"]["Name"];
var email = document.forms["RegForm"]["EMail"];
var phone = document.forms["RegForm"]["Telephone"];
var what = document.forms["RegForm"]["Subject"];
var password = document.forms["RegForm"]["Password"];
var address = document.forms["RegForm"]["Address"];

if (name.value == "") {
window.alert("Please enter your name.");
name.focus();
return false;
}

if (address.value == "") {
window.alert("Please enter your address.");
address.focus();
return false;
}

if (email.value == "") {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (email.value.indexOf("@", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (email.value.indexOf(".", 0) < 0) {
window.alert("Please enter a valid e-mail address.");
email.focus();
return false;
}

if (phone.value == "") {
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}

if (password.value == "") {
window.alert("Please enter your password");
password.focus();
return false;
}

if (what.selectedIndex < 1) {
alert("Please enter your course.");
what.focus();
return false;
}

return true;
}
</script>

<style>
ValidateCode {
margin-left: 70px;
font-weight: bold;
float: left;
clear: left;
width: 100px;
text-align: left;
margin-right: 10px;
font-family: sans-serif, bold, Arial, Helvetica;
font-size: 14px;
}

div {
box-sizing: border-box;
width: 100%;
border: 100px solid black;
float: left;
align-content: center;
align-items: center;
}

form {
margin: 0 auto;
width: 600px;
}
</style>
</head>
<body>
<h1 style="text-align: center">REGISTRATION FORM</h1>
<form
name="RegForm"
action="/submit.php"
onsubmit="return ValidateCode()"
method="post"
>
<p>Name: <input type="text" size="65" name="Name" /></p>
<br />
<p>Address: <input type="text" size="65" name="Address" /></p>
<br />
<p>E-mail Address: <input type="text" size="65" name="EMail" /></p>
<br />
<p>Password: <input type="text" size="65" name="Password" /></p>
<br />
<p>Telephone: <input type="text" size="65" name="Telephone" /></p>
<br />

<p>
SELECT YOUR COURSE
<select type="text" value="" name="Subject">
<option>BTECH</option>
<option>BBA</option>
<option>BCA</option>
<option>B.COM</option>
<option>ValidateCode</option>
</select>
</p>
<br /><br />
<p>Comments: <textarea cols="55" name="Comment"> </textarea></p>
<p>
<input type="submit" value="send" name="Submit" />
<input type="reset" value="Reset" name="Reset" />
</p>
</form>
</body>
</html>
Output:

13. Create a table to hold details of a Book (book_id number, book_name


varchar2(20), pages number) using Oracle database. Write a Java JDBC
Program to Insert the data
into the Book table by using the Statement Interface.

importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_insert {

publicstaticvoidmain(String[] args) throwsClassNotFoundException {


Connectioncon=null;
Statementstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con
=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager")
;
System.out.println("Connection established");

Scanners=newScanner(System.in);
System.out.println("Enter the book id :");
intbook_id=s.nextInt();

System.out.println("Enter the book name :");


Stringbook_name=s.next();

System.out.println("Enter the book page number :");


intbook_page=s.nextInt();

Stringinsert="insert into book


values("+book_id+",'"+book_name+"',"+book_page+")";
stmt=con.createStatement();
stmt.executeUpdate(insert);

System.out.println("Data inserted.");

}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}

finally
{
System.out.println("All resources released");
}

SQL
create table book(
book_id number,
book_name varchar2(30),
book_price number);

insert into book values (1,'Java', 150);


insert into book values (2,'C++', 250);
insert into book values (3,'Python', 300);
insert into book values (4,'DBMS', 100);
insert into book values (5,'Javascript', 200);
commit;

Output:

14. Write a Java JDBC Program to Insert the data into the Book table by using
the Prepared Statement Interface.
importjava.sql.*;
importjava.util.Scanner;

publicclassMyPreparedStmt {

publicstaticvoidmain(String[] args) throwsClassNotFoundException {


// TODO Auto-generated method stub

Connectioncon=null;
PreparedStatementpstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");

Stringinsert="insert into BOOK values(?,?,?)";


pstmt=con.prepareStatement(insert);

Scanners=newScanner(System.in);
System.out.println("Enter the book id : ");
intbook_id=s.nextInt();
System.out.println("Enter the book name : ");
Stringbook_name=s.next();
System.out.println("Enter the book price : ");
intbook_price=s.nextInt();

pstmt.setInt(1, book_id);
pstmt.setString(2, book_name);
pstmt.setInt(3, book_price);

pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}

}
Output:

15. Write a Java JDBC Program to Delete the data from the Book table by
using the Statement Interface.
importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_delete {

publicstaticvoidmain(String[] args) throwsClassNotFoundException {


Connectioncon=null;
Statementstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");

stmt=con.createStatement();
Scanners=newScanner(System.in);
System.out.println("Enter the Book id : ");
intbook_id=s.nextInt();

Stringdelete="delete from book where book_id ="+book_id;


stmt.executeUpdate(delete);
System.out.println("Rows deleted.");
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}

finally
{
System.out.println("All resources released");
}
}
}

Output:

16. Write a Java JDBC Program to Delete the data from the Book table by
using the Prepared Statement Interface.
importjava.sql.*;
importjava.util.Scanner;

publicclassPrepare_Delete {

publicstaticvoidmain(String[] args) throwsClassNotFoundException {


Connectioncon=null;
PreparedStatementpstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");

Stringdelete="delete from BOOK where book_id=?";


Scanners=newScanner(System.in);
System.out.println("Enter the BOOK id : ");
intBOOK_id=s.nextInt();

pstmt=con.prepareStatement(delete);
pstmt.setInt(1, BOOK_id);
pstmt.executeUpdate();

System.out.println("Data Deleted.");
con.close();
pstmt.close();
}

catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}

Output:
17. Write a Java JDBC Program to Update the data from the Book table by
using the Statement Interface.

importjava.sql.*;
importjava.util.Scanner;
publicclassJDBC_update {

publicstaticvoidmain(String[] args) throwsClassNotFoundException{


Connectioncon=null;
Statementstmt=null;
intstud_id;
Stringstud_name;
intstud_phone;

try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");
Scanners=newScanner(System.in);
System.out.println("Enter the Book Id: ");
intbook_id=s.nextInt();

System.out.println("Enter the Book Name: ");


Stringbook_name=s.next();

System.out.println("Enter the Book Page: ");


intbook_page=s.nextInt();

Stringupdate="update book set book_name = '"+book_name


+"', book_price ="+book_page+" where book_id ="+book_id;
stmt=con.createStatement();
stmt.executeUpdate(update);
System.out.println("Rows updated");

con.close();
stmt.close();
}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}
}

Output:

18. Write a Java JDBC Program to Update the data from the Book table by
using the Prepared Statement Interface.

importjava.sql.*;
importjava.util.Scanner;
publicclassPrepareUpdate {

publicstaticvoidmain(String[] args) throwsClassNotFoundException{


Connectioncon=null;
PreparedStatementpstmt=null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manag
er");
System.out.println("Connection established");

Stringupdate="update BOOK set BOOK_NAME =? , BOOK_PRICE =? where BOOK_ID


=?";
pstmt=con.prepareStatement(update);
Scanners=newScanner(System.in);
System.out.println("Enter the BOOK id : ");
intbook_id=s.nextInt();
System.out.println("Enter the BOOK name : ");
Stringbook_name=s.next();
System.out.println("Enter the BOOK price : ");
intbook_price=s.nextInt();

pstmt.setString(1,book_name);
pstmt.setInt(2, book_price);
pstmt.setInt(3, book_id);

pstmt.executeUpdate();
System.out.println("Data Updated.");

}
catch(SQLExceptionse)
{
System.out.println(se.getMessage());
}
finally
{
System.out.println("All resources released");
}

Output:

19. Write a Menu Driven program to perform Insert, Update and Delete by
using the Statement Interface.
1. Insert
2. Delete
3. Update
4. Exit

import java.sql.*;
import java.util.Scanner;

public class JDBC_ALL {

static Connection con=null;


static Statement stmt = null;

public void openConnection()


{
try
{
// load oracle driver

Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

public void closeConnection()


{
try
{
con.close();
stmt.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
}

public static void main(String[] args) {


// TODO Auto-generated method stub

System.out.println("Menu Driven Program");


System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Update");
System.out.println("4. Exit");
System.out.println("What do you want to do ?");
Scanner s = new Scanner(System.in);
int choice = s.nextInt();
JDBC_ALL ja = new JDBC_ALL();
ja.openConnection();

switch(choice)
{
case 1:
try
{

System.out.println("Enter the book id :");


int book_id = s.nextInt();

System.out.println("Enter the book name :");


String book_name = s.next();

System.out.println("Enter the book page number :");


int book_page = s.nextInt();

String insert = "insert into book values(" + book_id +


",'" + book_name + "'," + book_page +")";
stmt = con.createStatement();
stmt.executeUpdate(insert);

System.out.println("Data inserted.");

}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;

case 2 :
try
{

stmt = con.createStatement();
System.out.println("Enter the Book id : ");
int book_id = s.nextInt();

String delete = "delete from book where book_id ="


+book_id;
stmt.executeUpdate(delete);
System.out.println("Rows deleted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}

break;
case 3 :
try
{
System.out.println("Enter the Book Id of which you
want to update data");
int book_id = s.nextInt();

System.out.println("Enter the Book Name: ");


String book_name = s.next();

System.out.println("Enter the Book Page: ");


int book_page = s.nextInt();

String update = "update book set book_name = '"


+book_name
+ "', book_price ="+book_page+ " where
book_id =" +book_id;
stmt = con.createStatement();
stmt.executeUpdate(update);
System.out.println("Rows updated");

}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break ;

case 4: System.exit(0);
}

ja.closeConnection();

}
}

Output:

20. Write a Menu Driven program to perform Insert, Update and Delete by
using the Prepared Statement Interface.
1. Insert
2. Delete
3. Update
4. Exit
import java.sql.DriverManager;
import java.sql.* ;
import java.util.Scanner ;
public class JDBC_ALL {

static Connection con = null;


static PreparedStatementpstmt = null;
static ResultSetrs = null;

public void openConnection()


{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","Sarangdixit
@2001");
System.out.println("Connection established");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

public void closeConnection()


{
try
{
con.close();
pstmt.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
}

public static void main(String[] args) throws ClassNotFoundException{


// TODO Auto-generated method stub

int bid,bprice;
String bname;

System.out.println("Menu Driven Program using PreparedStatement");


System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Update");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.println("What do you want to do ?");

Scanner s = new Scanner(System.in);


int choice = s.nextInt();

JDBC_ALL ja = new JDBC_ALL();


ja.openConnection();

switch(choice)
{
case 1:
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");

String insert = "insert into BOOK values(?,?,?)";


pstmt = con.prepareStatement(insert);

System.out.println("Enter the book id : ");


int book_id = s.nextInt();
System.out.println("Enter the book name : ");
String book_name = s.next();
System.out.println("Enter the book price : ");
int book_price = s.nextInt();

pstmt.setInt(1, book_id);
pstmt.setString(2, book_name);
pstmt.setInt(3, book_price);

pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;

case 2:

try {
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");
String delete ="delete from BOOK where book_id=?";

System.out.println("Enter the BOOK id : ");


int BOOK_id = s.nextInt();

pstmt = con.prepareStatement(delete);
pstmt.setInt(1, BOOK_id);
pstmt.executeUpdate();

System.out.println("Data Deleted.");
con.close();
pstmt.close();
}
catch (SQLException se) {
System.out.println(se.getMessage());
}
break;

case 3 :
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");

String update = "update BOOK set BOOK_NAME =? ,


BOOK_PRICE =? where BOOK_ID =?";
pstmt = con.prepareStatement(update);

System.out.println("Enter the BOOK id : ");


int book_id = s.nextInt();
System.out.println("Enter the BOOK name : ");
String book_name = s.next();
System.out.println("Enter the BOOK price : ");
int book_price = s.nextInt();

pstmt.setString(1,book_name);
pstmt.setInt(2, book_price);
pstmt.setInt(3, book_id);

pstmt.executeUpdate();
System.out.println("Data Updated.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;

case 4 :
try
{
String select = "Select * from BOOK";
pstmt = con.prepareStatement(select);
rs = pstmt.executeQuery(select);
while(rs.next())
{
System.out.println("Book Id :"+rs.getInt("bid"));
System.out.println("Book
Name :"+rs.getString("bname"));
System.out.println("Book Pages :"+rs.getInt("bpages"));
}
rs.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
break;

case 5:
System.exit(0);
break;
}
ja.closeConnection();

}
}

Output:
21. Design an application using JSP and Servlet to insert the data in the Book
table.

JSP FILE :
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="InsertServelet" method="post">
Book ID :<input type="text" name="bid"><br/><br/>
Book Name :<input type="text" name="bname"><br/><br/>
Book Price :<input type="text" name="bprice"><br/><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>

SERVELET CODE:
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;

/**
* Servlet implementation class InsertServelet
*/
public class InsertServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InsertServelet() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);

Connection con = null;


PreparedStatementpstmt = null;

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");

String insert = "insert into BOOK values(?,?,?)";


pstmt = con.prepareStatement(insert);

int bid = Integer.parseInt(request.getParameter("bid"));


String bname = request.getParameter("bname");
int bprice = Integer.parseInt(request.getParameter("bprice"));

pstmt.setInt(1, bid);
pstmt.setString(2, bname);
pstmt.setInt(3, bprice);

pstmt.executeUpdate();
System.out.println("Data Inserted.");
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Output:
22. Design an application using JSP and Servlet to delete the data
from the Book table.
JSP CODE:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Delete" method="post">
<h1><b>ENTER THE ID OF THE BOOK WHICH YOU WANT TO DELETE</b></h1>
Book ID :<input type="text" name="bid"><br/><br/>
<input type="submit" value="DELETE">
</form>
</body>
</html>

SERVELET CODE:

import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* Servlet implementation class Delete
*/
public class Delete extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Delete() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at:
").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);

Connection con = null;


PreparedStatementpstmt = null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");

String delete ="delete from BOOK where book_id=?";

int bid = Integer.parseInt(request.getParameter("bid"));

pstmt = con.prepareStatement(delete);
pstmt.setInt(1, bid);
pstmt.executeUpdate();

System.out.println("Data Deleted.");
response.getWriter().append("Data Deleted Successfully");
con.close();
pstmt.close();
}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

Output:

23. Design an application using JSP and Servlet to update the data from the
Book table.

JSP CODE :
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Update" method="post">
<h1><b>ENTER THE ID OF THE BOOK WHICH YOU WANT TO UPDATE THE
DETAILS</b></h1><br/><br/>
Book ID :<input type="text" name="bid"><br/><br/>
New Book Name :<input type="text" name="bname"><br/><br/>
New Book Price :<input type="text" name="bprice"><br/><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>

SERVELET CODE :

import java.sql.*;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
* Servlet implementation class Update
*/
public class Update extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public Update() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);

Connection con = null;


PreparedStatementpstmt = null;
try
{
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
System.out.println("Connection established");

String update = "update BOOK set BOOK_NAME =? , BOOK_PRICE =?


where BOOK_ID =?";
pstmt = con.prepareStatement(update);

int bid = Integer.parseInt(request.getParameter("bid"));


String bname = request.getParameter("bname");
int bprice = Integer.parseInt(request.getParameter("bprice"));

pstmt.setString(1,bname);
pstmt.setInt(2, bprice);
pstmt.setInt(3, bid);

pstmt.executeUpdate();
System.out.println("Data Updated.");

}
catch(SQLException se)
{
System.out.println(se.getMessage());
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

}
Output:

24. Design an application using JSP and Servlet to display the data from the
Book table.

JSP Page (displayBooks.jsp):


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Display Books</title>
</head>
<body>
<h1>Book List</h1>
<table border="1">
<tr>
<th>Book ID</th>
<th>Book Name</th>
<th>Book Price</th>
</tr>
<%
// Import necessary classes for database connection and querying
// Perform database connection and query to fetch book data

try {
// Establish database connection
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM BOOK");

while (rs.next()) {
%>
<tr>
<td><%= rs.getInt("BOOK_ID") %></td>
<td><%= rs.getString("BOOK_NAME") %></td>
<td><%= rs.getInt("BOOK_PRICE") %></td>
</tr>
<%
}
// Close the resources
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
out.println("Error: " + e.getMessage());
}
%>
</table>
</body>
</html>

Servlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DisplayBooksServlet")
public class DisplayBooksServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
try {
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"manager");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM BOOK");

request.setAttribute("bookResultSet", rs); // Set the result set as an attribute

rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}

request.getRequestDispatcher("displayBooks.jsp").forward(request, response);
}
}

Output:

25. Design an application using JSP and Servlet to insert, update, delete and
display the data from the Book table.
Prepare a file with the Title Page and Index Page
Title Page should contain your name, PRN Number, Division etc.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="form1" action="BookServlet2" method="post">
Book Id : <input type="text" name ="bid">
<br/>
Book Name : <input type="text" name ="bname">
<br/>
Book Pages : <input type="text" name ="bpages">
<br/>
<input type="submit" name ="button1" value="Insert">
<input type="submit" name ="button1" value="Update">

<input type="submit" name ="button1" value="Delete">


<input type="submit" name ="button1" value="Show">
</form>
</body>
</html>

Servlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
* Servlet implementation class BookServlet
*/
public class BookServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public BookServlet2() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);

String action = request.getParameter("button1");


System.out.println(action);
String action1 = action.trim();
System.out.println(action1);
Connection con = null;
ResultSet res = null;
Statement stmt = null;
PreparedStatement pstmt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
// connect using Thin driver
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"Tejashree");
System.out.println("Connection established");
if (action1.equals("Insert")) {
System.out.println("Inserting");
String insert = "insert into book1 values (?,?,?)";
pstmt = con.prepareStatement(insert);

// Read the data from the textboxes


String bid = request.getParameter("bid");
int bid1 = Integer.parseInt(bid);
String bname = request.getParameter("bname");

String bpages = request.getParameter("bpages");


int bpages1 = Integer.parseInt(bpages);

pstmt.setInt(1, bid1);
pstmt.setString(2, bname);
pstmt.setInt(3, bpages1);
pstmt.executeUpdate();

PrintWriter out = response.getWriter();


out.print("Inserted the data");
} else if (action1.equals("Update")) {
String bid = request.getParameter("bid");
int bid1 = Integer.parseInt(bid);

String bname = request.getParameter("bname");

String bpages = request.getParameter("bpages");


int bpages1 = Integer.parseInt(bpages);

String update = "update book1 set bname = ? , bpages = ? where bid =?";
pstmt = con.prepareStatement(update);

pstmt.setString(1, bname);
pstmt.setInt(2, bpages1);
pstmt.setInt(3, bid1);

pstmt.executeUpdate();
PrintWriter out = response.getWriter();
out.print("Updated the data");
} else if (action1.equals("Delete")) {
String bid = request.getParameter("bid");
int bid1 = Integer.parseInt(bid);

String delete = "delete from book1 where bid =?";

pstmt = con.prepareStatement(delete);
pstmt.setInt(1, bid1);
pstmt.executeUpdate();

PrintWriter out = response.getWriter();


out.print("Deleted the data");
} else if (action1.equals("Show")) {
String select = "Select * from book1";
stmt = con.createStatement();
res = stmt.executeQuery(select);

PrintWriter out = response.getWriter();


out.print("<html>");
out.print("<title> Book Data </title>");
out.print("<body>");
out.print("<table border=1>");
out.print("<th> Book Id </th>");
out.print("<th> Book Name </th>");
out.print("<th> Book Pages </th>");
while (res.next()) {
out.print("<tr>");
out.print("<td>");
out.print(res.getInt("bid"));
out.print("</td>");
out.print("<td>");
out.print(res.getString("bname"));
out.print("</td>");

out.print("<td>");
out.print(res.getInt("bpages"));
out.print("</td>");
out.print("</tr>");
}

out.print("</table>");
out.print("</body>");
out.print("</html>");

}
} catch (SQLException se) {
System.out.println(se.getMessage());
} catch (Exception se) {
System.out.println(se.getMessage());
}
}

}
Output:

-------------------------------------------------------------------------------------------------------------

You might also like