0% found this document useful (0 votes)
9 views5 pages

Ipwt 3

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)
9 views5 pages

Ipwt 3

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/ 5

25)Describe the steps to establish a connection to a database using JDBC.

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the
driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the classpath, and
then JDBC driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement is responsible
to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the
object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of Connection
interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();

26)Explain the usage of basic DDL and DML statements in SQL


In SQL (Structured Query Language), DDL (Data Definition Language) and DML (Data Manipulation Language)
statements are used to define, modify, and manipulate the structure and data of databases. Here's a brief explanation of
their usage:
DDL (Data Definition Language):
DDL statements are used to define and manage the structure of database objects such as tables, indexes, views, and
schemas.
Common DDL statements include:
CREATE: Used to create new database objects such as tables, indexes, or views. For example, CREATE TABLE,
CREATE INDEX.

ALTER: Used to modify the structure of existing database objects. For example, ALTER TABLE, ALTER INDEX.
DROP: Used to delete existing database objects. For example, DROP TABLE, DROP INDEX.
TRUNCATE: Used to remove all records from a table, but keep the table structure intact.
RENAME: Used to rename an existing database object. For example, RENAME TABLE.
Example:
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT );
DML (Data Manipulation Language):
DML statements are used to manipulate the data stored in database objects such as tables.
Common DML statements include:
SELECT: Used to retrieve data from one or more tables. It is not strictly a DML statement but is commonly
categorized as such.
INSERT: Used to add new records to a table. For example, INSERT INTO.
UPDATE: Used to modify existing records in a table. For example, UPDATE.
DELETE: Used to remove records from a table. For example, DELETE FROM.
Example:
INSERT INTO Employees (EmpID, FirstName, LastName, Age)
VALUES (1, 'John', 'Doe', 30);
27)Differentiate between Statement, PreparedStatement, and CallableStatement.

28) Demonstrate JDBC program to display STUDENT table.


import java.sql.*; int age = resultSet.getInt("Age");
public class DisplayStudentTable { String grade =
public static void main(String[] args) { resultSet.getString("Grade");
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String username = "your_username"; System.out.println(id + "\t" + name +
String password = "your_password"; "\t\t" + age + "\t" + grade); }
String sql = "SELECT * FROM STUDENT";
try { resultSet.close();
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password); statement.close();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql); connection.close();
System.out.println("Student Table:"); } catch (Exception e) {
System.out.println("ID\tName\t\tAge\tGrade");
while (resultSet.next()) { e.printStackTrace(); }}}
int id = resultSet.getInt("ID");
String name = resultSet.getString("Name");
29)Develop SQL Statements for the following tables using suitable datatypes and constraints as specified below
in ORACLE database Department(DeptID, DName) ; Primary Key : DeptID ,Course (CourseID,
CourseName,Credits) ; Primary Key : CourseID ,Regsitration(StudentID, CourseCode,BranchID);Primary Key
: StudentID Foreign key(s):CourseCode Course(CourseID), BranchID Department(DeptID) .Write sql queries
for the following 1.Display all courses registered by a student along with course name and credits 2.Display all
students of “IoT" branch
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DName VARCHAR(100) );
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100),
Credits INT );
CREATE TABLE Registration (
StudentID INT,
CourseCode INT,
BranchID INT,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode) REFERENCES Course(CourseID),
FOREIGN KEY (BranchID) REFERENCES Department(DeptID) );
Display all courses registered by a student along with course name and credits:
SELECT R.StudentID, C.CourseName, C.Credits
FROM Registration R
JOIN Course C ON R.CourseCode = C.CourseID
WHERE R.StudentID = <student_id>;
Display all students of “IoT" branch:
SELECT R.StudentID
FROM Registration R
JOIN Department D ON R.BranchID = D.DeptID
WHERE D.DName = 'IoT';
30)Assume a table Employees with following fields (Empid, FirstName, LastName, Department) in ORACLE
database. Write SQL statements to create the above table and • Insert 4 records into the above table • Display the
Last Name of all employees. • Select all the data of employees whose FirstName is "Smith" or "Doe". • Update
the Lastname of Employee 7788 as “Kluever”. • Delete the record(s) of employee 7654. • Display all the employees
who work in department 30.
CREATE TABLE Employees (
Empid INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50) );
INSERT INTO Employees (Empid, FirstName, LastName, Department)
VALUES (7369, 'John', 'Smith', 'IT');
INSERT INTO Employees (Empid, FirstName, LastName, Department)
VALUES (7499, 'Adam', 'Doe', 'HR');
INSERT INTO Employees (Empid, FirstName, LastName, Department)
VALUES (7521, 'Mary', 'Smith', 'Finance');
INSERT INTO Employees (Empid, FirstName, LastName, Department)
VALUES (7788, 'Chris', 'Jones', 'IT');
Display Last Names of all Employees:
SELECT LastName FROM Employees;
Select Data of Employees whose FirstName is "Smith" or "Doe":
SELECT * FROM Employees WHERE FirstName IN ('Smith', 'Doe');
Update Last Name of Employee 7788 to "Kluever":
UPDATE Employees SET LastName = 'Kluever' WHERE Empid = 7788;
Delete Record(s) of Employee 7654:
DELETE FROM Employees WHERE Empid = 7654;
Display all Employees who work in department 30:
SELECT * FROM Employees WHERE Department = '30';
31)Explain the translation phase and request processing phase involved in processing a JSP page by a web server
When a JSP (JavaServer Pages) page is requested by a client, it goes through two main phases in the web server: the
translation phase and the request processing phase.
Translation Phase: In the translation phase, the JSP container translates the JSP page into a servlet class.
The translation process involves the following steps:
Parsing: The JSP container parses the JSP page to identify static content (HTML markup) and dynamic content (Java
code embedded within <% %> tags).
Compilation: The JSP container compiles the parsed JSP page into a Java servlet class.
Class Generation: The container generates a Java servlet class from the compiled JSP page. This servlet class extends
the HttpServlet class and overrides the doGet() or doPost() method to process HTTP requests.
Compilation Errors Handling: If there are any compilation errors in the JSP page, the container reports them to the
developer for correction.
Request Processing Phase: In the request processing phase, the servlet container executes the generated servlet class
to process the client's request. The request processing phase involves the following steps:
Instantiation: The servlet container instantiates an object of the generated servlet class to handle the client's request.
Initialization: The container calls the init() method of the servlet to perform any initialization tasks. This method is
called only once during the servlet's lifecycle.
Service Method Invocation: The container calls the service() method of the servlet, passing the HTTP request and
response objects as parameters. Depending on the type of HTTP request (GET, POST, etc.), the service() method
dispatches the request to the appropriate doGet(), doPost(), or other methods defined in the servlet.
Response Generation: The servlet processes the client's request, generates dynamic content (if any), and sends the
response back to the client via the HttpServletResponse object.
Destruction: After serving the request, the container calls the destroy() method of the servlet to perform any cleanup
tasks. This method is called only once during the servlet's lifecycle, typically when the servlet container shuts down or
reloads the application.
32)Identify the methods involved in Servlet Life Cycle and explain their usage.
The Servlet API defines several methods that are involved in the lifecycle of a servlet. These methods are called by the
servlet container at various stages of the servlet's lifecycle. Below are the main methods involved in the servlet lifecycle
and their usage:
init(): The init() method is called by the servlet container when the servlet is first initialized.
This method is typically used to perform one-time initialization tasks, such as loading configuration data or
establishing database connections.
The init() method is called only once during the lifecycle of a servlet, immediately after the servlet is instantiated.
service(): The service() method is called by the servlet container to handle client requests.
This method receives HttpServletRequest and HttpServletResponse objects as parameters, representing the client's
request and the response to be sent back to the client.
The service() method determines the type of HTTP request (GET, POST, etc.) and dispatches the request to the
appropriate doGet(), doPost(), or other methods defined in the servlet.
doGet() / doPost() / doPut() / doDelete(), etc.: These are the HTTP-specific methods called by the service() method
to handle different types of HTTP requests (GET, POST, PUT, DELETE, etc.).
Servlets override these methods to provide custom request handling logic for each type of HTTP request.
For example, the doGet() method is called to handle HTTP GET requests, while the doPost() method is called to
handle HTTP POST requests.
destroy(): The destroy() method is called by the servlet container when the servlet is about to be unloaded or taken
out of service.
This method is typically used to perform cleanup tasks, such as releasing database connections or closing resources.
The destroy() method is called only once during the lifecycle of a servlet, immediately before the servlet is destroyed.
33)Develop Servlet code to validate the Credit Card Expiration Year selected by the user through HTML form.
If valid then display a message “Valid Card” else “ Card Expired “ . (Assume the Card Expiration Year is 2027)
import java.io.IOException;
import java.io.PrintWriter;
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("/ValidateCreditCardServlet")
public class ValidateCreditCardServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String expirationYearStr = request.getParameter("expirationYear");
int currentYear = 2027;
try {
int expirationYear = Integer.parseInt(expirationYearStr);
if (expirationYear >= currentYear) {
out.println("<html><body>");
out.println("<h2>Valid Card</h2>");
out.println("</body></html>");
} else {
out.println("<html><body>");
out.println("<h2>Card Expired</h2>");
out.println("</body></html>"); }
} catch (NumberFormatException e) {
out.println("<html><body>");
out.println("<h2>Invalid Year</h2>");
out.println("</body></html>");
}}}
34)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”.
<!DOCTYPE html>
<html>
<head>
<title>Mobile Number Validation</title>
<script>
function validateMobileNumber() {
var mobileNumber = document.getElementById("mobileNumber").value;
var regex = /^\d{10}$/;
if (regex.test(mobileNumber)) {
document.getElementById("message").innerHTML = "Thanks for providing your contact number";
return true; // Valid mobile number
} else {
document.getElementById("message").innerHTML = "Invalid Mobile Number";
return false; // Invalid mobile number }}
</script>
</head>
<body>
<h2>Mobile Number Validation</h2>
<form onsubmit="return validateMobileNumber()">
<label for="mobileNumber">Enter Mobile Number:</label>
<input type="text" id="mobileNumber" name="mobileNumber">
<input type="submit" value="Submit">
</form>
<p id="message"></p>
</body>
</html>

You might also like