Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
31 views22 pages

Ipw 1&2

Uploaded by

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

Ipw 1&2

Uploaded by

Sandeep Barukula
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

1)Illustrate the importance of Class.forName() and DriverManager.getConnection() methods of JDBC API?

A)Importance of Class.forName(): The Class.forName() method is used to dynamically load the JDBC driver
class into memory. In JDBC, each database vendor provides its own implementation of the JDBC driver, which
is responsible for facilitating communication between the Java application and the specific database
management system (DBMS). By using Class.forName(), the driver class is loaded and registered with the
DriverManager, allowing it to be used to establish connections to the corresponding database.
try {
// Dynamically load the JDBC driver class
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Importance of DriverManager.getConnection():
The DriverManager.getConnection() method is used to establish a connection to the database using the
registered JDBC driver. It takes a database URL, username, and password as parameters and returns a
Connection object representing the connection to the database. This connection object is then used to create
statements, execute queries, and perform other database operations.
try {
// Establish connection to the database
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// Perform database operations using the connection
// Close the connection when done
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}

2) List out the advantages of Type IV JDBC Driver?A


A)A Type IV JDBC (Java Database Connectivity) driver, also known as the "thin driver" or "pure Java driver," is a
JDBC driver type that communicates directly with the database server without requiring any native code or
middleware. Here are some advantages of using a Type IV JDBC Driver:
Platform Independence: Type IV drivers are written entirely in Java, making them platform-independent. They
can run on any platform that supports Java, including Windows, Linux, macOS, etc. This eliminates the need for
platform-specific libraries or configurations.
No Client Installation: Type IV drivers do not require any client-side installation. Since they are pure Java
implementations, they can be distributed along with the application code. This simplifies deployment and
reduces dependencies, making it easier to manage and maintain applications.
Optimal Performance: Type IV drivers offer optimal performance because they communicate directly with the
database server using the native network protocols provided by the database vendor. There is no intermediate
translation layer, which can introduce overhead and affect performance. This direct communication minimizes
latency and improves response times.
Security: Type IV drivers provide secure communication between the Java application and the database server.
They typically support encryption and authentication mechanisms provided by the database vendor, ensuring
the confidentiality and integrity of data transmitted over the network.
Scalability: Type IV drivers are scalable and can handle high volumes of database connections efficiently. They
leverage the scalability features of the underlying Java platform and database server, allowing applications to
scale seamlessly as the workload increases.
Ease of Development: Type IV drivers simplify development by providing a consistent and familiar JDBC API for
database access. Developers can write database-independent code using standard JDBC interfaces without
worrying about the underlying database implementation details.
3) Compare executeQuery() and executeUpdate() methods of ResultSet object with an example?

A)

4) Develop a JSP script that illustrates the usage of JSP expressions and JSP directives?

A)<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Example</title>
</head>
<body>
<!-- JSP Directive: Using 'page' directive to import a Java package -->
<%@ page import="java.util.Date" %>
<!-- JSP Expression: Displaying the current date and time -->
<h2>Current Date and Time:</h2>
<p><%= new Date() %></p>
<!-- JSP Expression: Arithmetic expression -->
<h2>Arithmetic Expression:</h2>
<p>2 + 3 = <%= 2 + 3 %></p>
<!-- JSP Expression: Concatenating strings -->
<h2>String Concatenation:</h2>
<p>Hello <%= "World" %>!</p>
<!-- JSP Directive: Using 'include' directive to include another JSP file -->
<%@ include file="footer.jsp" %>
</body>
</html>
5) Design the following tables using SQL .Use suitable datatypes and constraints as specified below in
ORACLE database Department(DeptID , Dname ,Location) ;Primary Key : DeptID Employees (Empid ,
FirstName, LastName, DeptNo ) ; Primary Key : EmpID Foreign Key : DeptNo Department(DeptID)
Projects(ProjectID,DeptID,Manager) Foreign Key(s) : DeptID
Department(DeptID);ManagerEmployees(Empid) Write SQL Queries for the following 1. Display all
employees working in deptno 20; 2. Display all projects of department 10 3. Display managers of all
Projects?
A)-- Create Department table
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
Dname VARCHAR(50),
Location VARCHAR(50)
);
-- Create Employees table
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DeptNo INT,
FOREIGN KEY (DeptNo) REFERENCES Department(DeptID)
);
-- Create Projects table
CREATE TABLE Projects (
ProjectID INT PRIMARY KEY,
DeptID INT,
Manager INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID)
);
-- Create ManagerEmployees table
CREATE TABLE ManagerEmployees (
EmpID INT,
FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)
);
-- Sample Data Insertion for testing
INSERT INTO Department (DeptID, Dname, Location) VALUES (10, 'Sales', 'New York');
INSERT INTO Department (DeptID, Dname, Location) VALUES (20, 'Marketing', 'Los Angeles');
INSERT INTO Employees (EmpID, FirstName, LastName, DeptNo) VALUES (1, 'John', 'Doe', 10);
INSERT INTO Employees (EmpID, FirstName, LastName, DeptNo) VALUES (2, 'Jane', 'Smith', 20);
INSERT INTO Projects (ProjectID, DeptID, Manager) VALUES (101, 10, 1);
INSERT INTO Projects (ProjectID, DeptID, Manager) VALUES (102, 20, 2);
INSERT INTO ManagerEmployees (EmpID) VALUES (1);
INSERT INTO ManagerEmployees (EmpID) VALUES (2);
>Display all employees working in deptno 20:
SELECT * FROM Employees WHERE DeptNo = 20;
>Display all projects of department 10:
SELECT * FROM Projects WHERE DeptID = 10;
>Display managers of all Projects:
SELECT p.ProjectID, e.FirstName, e.LastName
FROM Projects p
JOIN Employees e ON p.Manager = e.EmpID;
6) Assume a table Flights with following fields: ( FlightID, Source, Destination, DepartureDate , Fare) Write
SQL statements to create the above table and • Insert 4 records in to the above table. • Display all flights
from Hyderabad• Update the Fare of Flight AI721 to 8900 • Delete the record of the flight starting from
Delhi. • Display all Flight details departing today. • Display all flights from Mumbai to Vijayawada?
A)-- Create Flights table
CREATE TABLE Flights (
FlightID INT PRIMARY KEY,
Source VARCHAR(50),
Destination VARCHAR(50),
DepartureDate DATE,
Fare DECIMAL(10, 2)
);
-- Insert 4 records into the Flights table
INSERT INTO Flights (FlightID, Source, Destination, DepartureDate, Fare)
VALUES
(1, 'Hyderabad', 'Bangalore', '2024-03-30', 4500.00),
(2, 'Delhi', 'Mumbai', '2024-03-31', 5500.00),
(3, 'Mumbai', 'Chennai', '2024-03-30', 5000.00),
(4, 'Chennai', 'Hyderabad', '2024-03-31', 4800.00);
-- Display all flights from Hyderabad
SELECT * FROM Flights WHERE Source = 'Hyderabad';
-- Update the Fare of Flight AI721 to 8900
UPDATE Flights SET Fare = 8900.00 WHERE FlightID = 1;
-- Delete the record of the flight starting from Delhi
DELETE FROM Flights WHERE Source = 'Delhi';
-- Display all Flight details departing today
SELECT * FROM Flights WHERE DepartureDate = CURRENT_DATE;
-- Display all flights from Mumbai to Vijayawada
SELECT * FROM Flights WHERE Source = 'Mumbai' AND Destination = 'Vijayawada';

7) Define Servlet and Compare Generic Servlet and HTTP Servlet ?


A)Java Servlets are the Java programs that run on the Java-enabled web server or application server. They are
used to handle the request obtained from the web server, process the request, produce the response, and then
send a response back to the web server.

GenericServlet HttpServlet

It is defined by javax.servlet package. It is defined by javax.servlethttp package.

It describes protocol-independent servlet It describes protocol-dependent servlet.

GenericServiet is not dependent on any particular HttpServlet is a dependent protocol and is only used
protocol. It can be used with any protocol such as with HTTP protocol.
HTTP, SMTP, FTP, and so on.

All methods are concrete except the service() All methods are concrete (non-abstract). service() is
method. service() method is an abstract method. non-abstract method. service() can be replaced by
doGet() or doPost() methods.

The service method is abstract. The service method is non-abstract

It forwards and includes a request and is also It forwards and includes a request but it is not
possible to redirect a request. possible to redirect the request.

GenericServlet doesn’t allow session management HTTPServlet allows session management with
with cookies and HTTP sessions. cookies and HTTP sessions.
8) Demonstrate a JSP script that illustrates the usage of sendRedirect() method to redirect the user to
another page?
A)<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Redirect Example</title>
</head>
<body>
<h2>Redirect Example</h2>
<%
// Check some condition (for demonstration)
boolean redirect = true;
if (redirect) {
// Redirect to another page
response.sendRedirect("destination.jsp");
} else {
// Output some content if not redirected
%>
<p>You will not be redirected.</p>
<%
}
%>
</body>
</html>
Destination.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Destination Page</title>
</head>
<body>
<h2>Welcome to the Destination Page</h2>
<p>This is the page where you have been redirected.</p>
</body>
</html>
9) Assume Customer table in Oracle Database with following fields (CustID, CustName, Address, Mobile).
a) Create a HTML form to enter the data in to above fields along with submit button. b) Write JSP code to
insert data submitted by the user through the above HTML form into Customer Table?
A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Registration Form</title>
</head>
<body>
<h2>Customer Registration Form</h2>
<form action="insertCustomer.jsp" method="post">
<label for="custName">Name:</label>
<input type="text" id="custName" name="custName" required><br><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required><br><br>
<label for="mobile">Mobile:</label>
<input type="text" id="mobile" name="mobile" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
insertCustomer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Customer Data</title>
</head>
<body>
<h2>Insert Customer Data</h2>
<%
// Retrieve form data submitted by the user
String custName = request.getParameter("custName");
String address = request.getParameter("address");
String mobile = request.getParameter("mobile");
// JDBC Connection variables
String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";
// SQL query to insert data into Customer table
String sql = "INSERT INTO Customer (CustName, Address, Mobile) VALUES (?, ?, ?)";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password)
// Create PreparedStatement to execute SQL query
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, custName);
pstmt.setString(2, address);
pstmt.setString(3, mobile);
// Execute the query
int rowsInserted = pstmt.executeUpdate();
if (rowsInserted > 0) {
out.println("<p>Customer data inserted successfully.</p>");
} else {
out.println("<p>Failed to insert customer data.</p>");
}
// Close PreparedStatement and Connection
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>"); }

%> </body> </html>


10) Assume Patients Table in Oracle Database with following fields ( PatientID, Pname, RoomNo, BedNo,
RefDoctor, JoinDate). a) Create a HTML Form that prompts the user to select a Date along with a submit
Button. b) Write Servlet code to display all the patient records who got admitted on a particular date as
selected by the user in HTML form?
A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select Admission Date</title>
</head>
<body>
<h2>Select Admission Date</h2>
<form action="PatientRecordsServlet" method="get">
<label for="admissionDate">Select Admission Date:</label>
<input type="date" id="admissionDate" name="admissionDate" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PatientRecordsServlet.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/PatientRecordsServlet")
public class PatientRecordsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve admission date selected by the user
String admissionDate = request.getParameter("admissionDate");
// JDBC Connection variables
String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";
// SQL query to select patient records based on admission date
String sql = "SELECT * FROM Patients WHERE JoinDate = ?";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);
// Create PreparedStatement to execute SQL query
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setDate(1, Date.valueOf(admissionDate)); // Convert String date to java.sql.Date
// Execute the query
ResultSet rs = pstmt.executeQuery();
// Display patient records
out.println("<h2>Patient Records for Admission Date: " + admissionDate + "</h2>");
out.println("<table border='1'>");
out.println("<tr><th>PatientID</th><th>Name</th><th>RoomNo</th><th>BedNo</th><th>RefDoctor</th><th
>JoinDate</th></tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("PatientID") + "</td>");
out.println("<td>" + rs.getString("Pname") + "</td>");
out.println("<td>" + rs.getString("RoomNo") + "</td>");
out.println("<td>" + rs.getString("BedNo") + "</td>");
out.println("<td>" + rs.getString("RefDoctor") + "</td>");
out.println("<td>" + rs.getDate("JoinDate") + "</td>");
out.println("</tr>");
}
out.println("</table>");
// Close ResultSet, PreparedStatement, and Connection
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}

11) Develop a Servlet script that receives and display the following data entered by the user through
HTML form - FirstName, LastName and Address?

A)import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/UserDetailsServlet")
public class UserDetailsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve user input data
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String address = request.getParameter("address");
// Display user details
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\">");
out.println("<title>User Details</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>User Details</h2>");
out.println("<p><strong>First Name:</strong> " + firstName + "</p>");
out.println("<p><strong>Last Name:</strong> " + lastName + "</p>");
out.println("<p><strong>Address:</strong> " + address + "</p>");
out.println("</body>");
out.println("</html>"); } }
12) Assume Books table in oracle database with following fields ( ISBN, Title, Author, Price) a) Create a
HTML that prompts the user to enter a Book Title and Updated Price along with a Submit Button. b) Write
Servlet code to Update the price of the book entered by the user.

A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Update Book Price</title>
</head>
<body>
<h2>Update Book Price</h2>
<form action="UpdateBookPriceServlet" method="post">
<label for="title">Book Title:</label>
<input type="text" id="title" name="title" required><br><br>
<label for="price">Updated Price:</label>
<input type="number" id="price" name="price" min="0" step="0.01" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
UpdateBookPriceServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/UpdateBookPriceServlet")
public class UpdateBookPriceServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve book title and updated price entered by the user
String title = request.getParameter("title");
double price = Double.parseDouble(request.getParameter("price"));
// JDBC Connection variables
String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";
// SQL query to update book price
String sql = "UPDATE Books SET Price = ? WHERE Title = ?";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);
// Create PreparedStatement to execute SQL query
PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setDouble(1, price);

pstmt.setString(2, title);

// Execute the query


int rowsUpdated = pstmt.executeUpdate();

if (rowsUpdated > 0) {

out.println("<p>Price updated successfully for book: " + title + "</p>");

} else {

out.println("<p>Failed to update price for book: " + title + "</p>");

}
// Close PreparedStatement and Connection
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}

13) Assume Customers table in oracle database with following fields ( CustID, CName, City, Mobile) a)
Create a HTML form that prompts the user to select city from a drop down list along with submit button.
b) Write JSP code to display the records of all customers who belongs to that city as selected by the user
through the HTML form?

A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select City</title>
</head>
<body>
<h2>Select City</h2>
<form action="DisplayCustomers.jsp" method="post">
<label for="city">Select City:</label>
<select id="city" name="city">
<option value="New York">New York</option>
<option value="Los Angeles">Los Angeles</option>
<option value="Chicago">Chicago</option>
<!-- Add more city options as needed -->
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
DisplayCustomers.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customers in City</title>
</head>
<body>
<h2>Customers in City</h2>
<%
// Retrieve selected city from the form
String city = request.getParameter("city");
// JDBC Connection variables
String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";
// SQL query to select customers in the selected city
String sql = "SELECT * FROM Customers WHERE City = ?";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);
// Create PreparedStatement to execute SQL query
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, city);
// Execute the query
ResultSet rs = pstmt.executeQuery();
// Display customer records
out.println("<table border='1'>");
out.println("<tr><th>CustID</th><th>CName</th><th>City</th><th>Mobile</th></tr>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("CustID") + "</td>");
out.println("<td>" + rs.getString("CName") + "</td>");
out.println("<td>" + rs.getString("City") + "</td>");
out.println("<td>" + rs.getString("Mobile") + "</td>");
out.println("</tr>");
}
out.println("</table>");
// Close ResultSet, PreparedStatement, and Connection
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
%>
</body>
</html>

14) Build JSP code to validate the mobile number entered by the user. A VALID mobile number has exactly
10 digits. If the mobile number is valid display the message “ Thanks for providing your contact number”
else display the message “ Invalid Mobile Number”?
A)<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mobile Number Validation</title>
</head>
<body>
<h2>Mobile Number Validation</h2>
<form action="MobileNumberValidation.jsp" method="post">
<label for="mobile">Enter Mobile Number:</label>
<input type="text" id="mobile" name="mobile" required><br><br>
<input type="submit" value="Validate">
</form>
<%
String mobileNumber = request.getParameter("mobile");
String message = "";
// Check if mobile number is exactly 10 digits
if (mobileNumber != null && mobileNumber.length() == 10 && mobileNumber.matches("\\d+")) {
message = "Thanks for providing your contact number";
} else {
message = "Invalid Mobile Number";
}
// Display validation message
out.println("<p>" + message + "</p>");
%>
</body>
</html>

15) Assume Users table in oracle database with following fields ( Username, Password) a) Create a HTML
form with Username and password Fields along with submit button. b) Develop JSP code that validates
the username and password fields and displays a welcome message for a valid user. (Assume a record
with username as ‘admin’ and password as “admin123’)
A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginValidation.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
LoginValidation.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Validation</title>
</head>
<body>
<h2>Login Validation</h2>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
// Hardcoded valid credentials
String validUsername = "admin";
String validPassword = "admin123";
// Validate username and password
if (username != null && password != null && username.equals(validUsername) &&
password.equals(validPassword)) {
// Display welcome message for valid user
%>
<p>Welcome, <%= username %>!</p>
<%
} else {
// Display error message for invalid user
%>
<p>Invalid username or password. Please try again.</p>
<%
}
%>
</body>
</html>
16) Explain the architecture of JDBC?

A)Architecture of JDBC

Description:
->Application: It is a java applet or a servlet that communicates with a data source.
->The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of
the important classes and interfaces defined in JDBC API are as follows:
->DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.
->JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently
communicates with the respective data source.
Types of JDBC Architecture(2-tier and 3-tier)
The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are as
described below:
Two-tier model: A java application communicates directly to the data source. The JDBC driver enables the
communication between the application and the data source. When a user sends a query to the data source,
the answers for those queries are sent back to the user in the form of results.
The data source can be located on a different machine on a network to which a user is connected. This is
known as a client/server configuration, where the user’s machine acts as a client, and the machine has the
data source running acts as the server.
Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the commands are
again sent to the data source. The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system directors.

17) Summarize various types of Statement objects used in JDBC?


A)In JDBC (Java Database Connectivity), there are three main types of Statement objects that can be used to
execute SQL queries and commands against a database:
Statement: This is the simplest type of Statement object, suitable for executing simple SQL queries without
parameters. It can execute SQL statements that do not contain input parameters or return multiple results.
However, it is vulnerable to SQL injection attacks and does not provide good performance for executing the
same SQL statement multiple times with different parameter values.
Example:
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
PreparedStatement: This type of Statement object allows for precompilation of SQL queries with parameters.
It is suitable for executing parameterized SQL queries, where the parameter values can be set dynamically
before execution. PreparedStatement provides better performance and security compared to Statement, as it
prevents SQL injection attacks by automatically escaping parameters. It is also more efficient for executing the
same SQL statement multiple times with different parameter values.
Example:
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM table_name WHERE
column_name = ?");
preparedStatement.setString(1, "parameter_value");
ResultSet resultSet = preparedStatement.executeQuery();
CallableStatement: This type of Statement object is used to execute stored procedures or functions in the
database. It allows for execution of SQL statements that are precompiled and stored in the database server.
CallableStatement is suitable for executing stored procedures or functions that may return multiple result sets
or have output parameters.
Example:
CallableStatement callableStatement = connection.prepareCall("{call procedure_name(?, ?)}");
callableStatement.setString(1, "input_parameter");
callableStatement.registerOutParameter(2, Types.INTEGER);
callableStatement.execute();
int outputParameter = callableStatement.getInt(2);

18) Develop a java program to select records from a table using JDBC application?
A) import java.sql.*;
public class SelectRecordsExample {
public static void main(String[] args) {
// JDBC Connection variables
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String username = "your_username";
String password = "your_password";
// SQL query to select records from EMP table
String sql = "SELECT * FROM EMP";
// Establish database connection
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Create a connection to the database


Connection connection = DriverManager.getConnection(url, username, password);
// Create a statement for executing SQL queries
Statement statement = connection.createStatement();
// Execute the SQL query and get the result set
ResultSet resultSet = statement.executeQuery(sql);
// Process the result set
while (resultSet.next()) {
// Retrieve data from each row
int empId = resultSet.getInt("emp_id");
String empName = resultSet.getString("emp_name");
double salary = resultSet.getDouble("salary");
String department = resultSet.getString("department");
// Print the retrieved data
System.out.println("Employee ID: " + empId);
System.out.println("Employee Name: " + empName);
System.out.println("Salary: " + salary);
System.out.println("Department: " + department);
System.out.println();
}
// Close the result set, statement, and connection
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

19) K L University maintains a library of Books written by their faculty members which are published by
different Publishers. Create a JDBC application that helps the librarian to perform some basic operations
like a) Adding a book to the database b) Fetching the details of the book including the Author information?

A) import java.sql.*;
public class LibraryManagementSystem {
// JDBC URL, username, and password
static final String JDBC_URL = "jdbc:mysql://localhost:3306/library";
static final String USERNAME = "your_username";
static final String PASSWORD = "your_password";
public static void main(String[] args) {
try {
// Establishing a connection to the database
Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
System.out.println("Connected to the database");
// Adding a book to the database
addBook(connection, "Introduction to Java", "John Smith", "ABC Publications");
// Fetching details of a book
fetchBookDetails(connection, "Introduction to Java");
// Closing the connection
connection.close();
System.out.println("Disconnected from the database");
} catch (SQLException e) {
e.printStackTrace();
}
}
// Method to add a book to the database
static void addBook(Connection connection, String title, String author, String publisher) throws SQLException
{
String sql = "INSERT INTO books (title, author, publisher) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, title);
statement.setString(2, author);
statement.setString(3, publisher);
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {

System.out.println("Book added successfully");


} else {
System.out.println("Failed to add book");
}
}
// Method to fetch details of a book including author information
static void fetchBookDetails(Connection connection, String title) throws SQLException {
String sql = "SELECT * FROM books WHERE title = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, title);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
String bookTitle = resultSet.getString("title");
String author = resultSet.getString("author");
String publisher = resultSet.getString("publisher");
System.out.println("Title: " + bookTitle);
System.out.println("Author: " + author);
System.out.println("Publisher: " + publisher);
} else {
System.out.println("Book not found");
}
}
}

20) An Admin of a Car selling company to add and view Car information details as per the design
specifications. The data received from the user (Admin) will be stored in database and retrieved when
required. Create required database and tables, to insert records into tables using JDBC application
Program?
A) CREATE DATABASE car_selling_company;
USE car_selling_company;
CREATE TABLE Cars (
CarID INT AUTO_INCREMENT PRIMARY KEY,
Brand VARCHAR(255) NOT NULL,
Model VARCHAR(255) NOT NULL,
Year INT NOT NULL,
Price DECIMAL(10, 2) NOT NULL
);
import java.sql.*;
public class CarSellingCompany {
public static void main(String[] args) {
// JDBC Connection variables
String url = "jdbc:mysql://localhost:3306/car_selling_company"; // Database URL
String username = "your_username";
String password = "your_password";
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create a connection to the database
Connection connection = DriverManager.getConnection(url, username, password);
// Inserting records into the Cars table
insertCar(connection, "Toyota", "Camry", 2022, 25000.00);
insertCar(connection, "Honda", "Civic", 2023, 22000.00);
insertCar(connection, "Ford", "Mustang", 2021, 35000.00);
// Retrieving and displaying car information from the Cars table
displayCars(connection);
// Close the connection
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Method to insert a car record into the Cars table
public static void insertCar(Connection connection, String brand, String model, int year, double price) throws
SQLException {
String sql = "INSERT INTO Cars (Brand, Model, Year, Price) VALUES (?, ?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, brand);
preparedStatement.setString(2, model);
preparedStatement.setInt(3, year);
preparedStatement.setDouble(4, price);
int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new car record was inserted successfully.");
}
preparedStatement.close();
}
// Method to retrieve and display all car records from the Cars table
public static void displayCars(Connection connection) throws SQLException {
String sql = "SELECT * FROM Cars";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int carID = resultSet.getInt("CarID");
String brand = resultSet.getString("Brand");
String model = resultSet.getString("Model");
int year = resultSet.getInt("Year");
double price = resultSet.getDouble("Price");
System.out.println("Car ID: " + carID + ", Brand: " + brand + ", Model: " + model + ", Year: " + year + ", Price: "
+ price);
}
resultSet.close();
statement.close();
}
}

21) Compare between JSP and Servlet?

Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation code.

Writing code for servlet is harder than JSP as it is


JSP is easy to code as it is java in HTML.
HTML in java.
Servlet JSP

JSP is the view in the MVC approach for showing


Servlet plays a controller role in the ,MVC approach.
output.

JSP is slower than Servlet because the first step in


Servlet is faster than JSP. the JSP lifecycle is the translation of JSP to java
code and then compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() method. In JSP, we cannot override its service() method.

In Servlet by default session management is not In JSP session management is automatically


enabled, user have to enable it explicitly. enabled.

In Servlet we have to implement everything like


In JSP business logic is separated from
business logic and presentation logic in just one
presentation logic by using JavaBeansclient-side.
servlet file.

Modification in Servlet is a time-consuming compiling


JSP modification is fast, just need to click the
task because it includes reloading, recompiling,
refresh button.
JavaBeans and restarting the server.

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

There is no method for running JavaScript on the While running the JavaScript at the client side in
client side in Servlet. JSP, client-side validation is used.

Packages are to be imported on the top of the Packages can be imported into the JSP program
program. (i.e, bottom , middleclient-side, or top )

It cannot handle extensive data processing very


It can handle extensive data processing.
efficiently.

The facility of writing custom tags is not present. The facility of writing custom tags is present.
22) Explain about various JSP Implicit Objects

A) JSP (JavaServer Pages) Implicit Objects are predefined objects that are automatically available to JSP pages
without needing to be explicitly declared or instantiated. These objects provide convenient access to various
components of the JSP environment, such as request, response, session, application, and more. Implicit
objects in JSP are accessible throughout the entire JSP page.
Here are the various implicit objects available in JSP:
request: This object represents the client's request to the server and provides access to parameters sent by the
client in the request. It allows JSP pages to retrieve form data, query parameters, and other information sent by
the client.
response: This object represents the server's response to the client and provides methods to set response
headers, status codes, and send content back to the client. It allows JSP pages to generate dynamic content to
be sent back to the client.
out: This object represents the output stream used to send content to the client. It is typically used to write
HTML content or other text-based data that will be included in the response sent to the client.
session: This object represents the user's session and provides access to session attributes, which are objects
stored on the server and associated with the user's session. It allows JSP pages to store and retrieve user-
specific data across multiple requests.
application: This object represents the servlet context or application context and provides access to
application-wide resources and configuration parameters. It allows JSP pages to share data and resources
across all users and sessions within the web application.
config: This object represents the configuration of the JSP page and provides access to initialization
parameters specified in the web deployment descriptor (web.xml). It allows JSP pages to retrieve configuration
settings specific to the current JSP page.
page: This object represents the current JSP page itself and provides access to various attributes and methods
related to the JSP page's execution environment. It allows JSP pages to perform operations such as forwarding
requests, including other resources, and accessing page-scoped attributes.
pageContext: This object represents the page context and provides access to all the other implicit objects, as
well as methods for managing page scope, request scope, session scope, and application scope attributes. It
serves as a bridge between JSP pages and the underlying servlet environment.

23) Develop a servlet code to illustrate the usage of getParameterValues() method of HTTPServletRequest
object?

A)import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ParameterValuesServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve parameter values sent from the client
String[] hobbies = request.getParameterValues("hobby");
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Parameter Values Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Selected Hobbies:</h2>");
out.println("<ul>");
if (hobbies != null) {
// Display each selected hobby
for (String hobby : hobbies) {
out.println("<li>" + hobby + "</li>");
}
} else {
out.println("<li>No hobbies selected</li>");
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
}

24) Assume Products table in oracle database with following fields ( PID, Pname, Manufacturer, Price) a)
Create a HTML form that prompts the user to select a Manufacturer Name from a Drop down list along
with submit Button. b) Build Servlet code to display all the products manufactured by the manufacturer
selected by the user through HTML form?

A)<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Select Manufacturer</title>
</head>
<body>
<h2>Select Manufacturer</h2>
<form action="DisplayProductsServlet" method="post">
<label for="manufacturer">Select Manufacturer:</label>
<select id="manufacturer" name="manufacturer">
<option value="Manufacturer A">Manufacturer A</option>
<option value="Manufacturer B">Manufacturer B</option>
<option value="Manufacturer C">Manufacturer C</option>
<!-- Add more manufacturer options as needed -->
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
DisplayProductsServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/DisplayProductsServlet")
public class DisplayProductsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// Retrieve selected manufacturer from the form
String manufacturer = request.getParameter("manufacturer");
// JDBC Connection variables
String url = "jdbc:oracle:thin:@localhost:1521:XE"; // Oracle database URL
String username = "your_username";
String password = "your_password";
// SQL query to select products by manufacturer
String sql = "SELECT * FROM Products WHERE Manufacturer = ?";
// Establish database connection
try {
Class.forName("oracle.jdbc.driver.OracleDriver"); // Load Oracle JDBC driver
Connection conn = DriverManager.getConnection(url, username, password);
// Create PreparedStatement to execute SQL query
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, manufacturer);
// Execute the query
ResultSet rs = pstmt.executeQuery();
// Display product details
out.println("<h2>Products Manufactured by " + manufacturer + ":</h2>");
out.println("<ul>");
while (rs.next()) {
out.println("<li>" + rs.getString("Pname") + " - " + rs.getString("Price") + "</li>");
}
out.println("</ul>");
// Close ResultSet, PreparedStatement, and Connection
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
out.println("<p>Error: " + e.getMessage() + "</p>");
}
}
}

You might also like