Advance Java Material
Advance Java Material
SRINIVAS GARAPATI
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 1
JDBC
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 2
Java Database Connectivity
JDBC:
• JDBC stands for Java Database Connectivity.
• JDBC API is a collection of classes and interfaces.
• JDBC API provides a way to connect with relational databases like Oracle, MySQl etc and
allow us to perform all Database operations.
• Standalone application: JDBC code need to write inside the class.
• Web application: JDBC code need to write inside the servlet.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 3
Loading the Driver
Connect with Database: There are 5 steps to including open and close connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(CS,User,Pwd);
Statement st = con.createStatement(); A
st.executeQueury(“select *from student”); M
con.close(); E
E
Driver class registration: Before the use of Driver, we must load and register the driver. R
Class.forName() P
• The most common approach to register a driver is to use Java's Class.forName() method. E
• Class.forName() method is to dynamically load the driver's class file into memory, which
T
automatically registers it.
package online; T
public class LoadDriver E
{
C
public static void main(String args[])
{ H
String driver = "oracle.jdbc.driver.OracleDriver"; N
try
O
{
Class.forName(driver); L
System.out.println("Driver loaded"); O
}
G
catch(ClassNotFoundException e1)
{ I
System.out.println("Exception : Driver is not present"); E
}
S
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 4
Connection to Database
DriverManager class:
• DriverManager class belongs to sql package.
• DriverManager providing static method called getConnection() to establish the
connection.
• getConnection() method takes the following input values and returns connection object
if the input values are valid.
• Password: It is the password given by the user at the time of installing the oracle
database.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 5
Program to establish the connection with Oracle DB from JDBC:
package online;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
public static void main(String args[]) throws SQLException
{
String driver = "oracle.jdbc.driver.OracleDriver";
Connection conn = null;
try
{
Class.forName(driver);
System.out.println("Driver loaded");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 6
Closing Connection using try-with-resources
• First you need to ensure that your JDBC driver supports AutoCloseable for Connection
objects.
• The Oracle JDBC driver does support AutoCloseable starting from Oracle Database 12c
Release 1 (12.1.0.2).
• If you are using an older version of the driver, you might need to manually close the
connection using the finally block.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class AutoCloseConnection
{
public static void main(String[] args)
{
String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:XE";
String username = "system";
String password = "admin";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
try (Connection connection = DriverManager.getConnection(jdbcUrl,
username, password))
{
System.out.println("Connection is ready");
}
catch (SQLException e)
{
System.out.println("Exception : " + e.getMessage());
}
}
catch (ClassNotFoundException e)
{
System.out.println("Exception : " + e.getMessage());
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 7
Connection & Statement Interfaces
Statement interface:
• The Statement interface provides methods to execute queries with the database.
• Commonly used methods of Statement interface:
ResultSet executeQuery(String sql) Is used to execute static DRL queries.
int executeUpdate(String sql) Is used to execute static DML queries.
boolean execute(String sql) Is used to execute static DDL queries.
int[] executeBatch() is used to execute batch of commands.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 8
Executing Static Queries using Statement interface
import java.sql.*;
public class CreateTable
{
public static void main(String args[]) throws Exception
{
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 9
Delete all records from Table (static query)
executeUpdate() method: it returns the number of rows affected by the SQL statement.
Consider the following table is present in Oracle database.
import java.sql.*;
public class DeleteRecords
{
public static void main(String args[]) throws Exception
{
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 10
Display all records from Database Table
exeuteQuery():
• executeQuery() method is used to execute DRL command
• executeQuery() method returns ResultSet object contains all records of that table.
• We process the data using ResultSet Object methods.
• Consider the following Account table with records.
ResultSet interface:
• ResultSet object returned by executeQuery() method or execute() method.
• ResultSet Object holds the records information collect through select query.
• The object of ResultSet maintains a cursor pointing to a row of a table.
• Initially, cursor points to before the first row.
package online;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 11
public class AccessData
{
public static void main(String args[]) throws Exception
{
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 12
ResultSetMetaData
Method Description
public int getColumnCount()throws It returns the total number of columns in the
SQLException ResultSet object.
public String getColumnName(int It returns the column name of the specified
index)throws SQLException column index.
public String getColumnTypeName(int It returns the column type name for the specified
index)throws SQLException index.
public String getTableName(int It returns the table name for the specified column
index)throws SQLException index.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 13
PreapraedStatement
PreparedStatement interface:
• It is the extension of Statement interface.
• It is used to execute parameterized query.
• PreparedStatement improve the performance because query is compiled only once.
• For example,
o String sql="insert into account values(?,?,?)";
Statement PreparedStatement
It is used to execute static sql It is used to execute sql statement many times.
queries
Doesn’t accept input parameters Access input parameters at runtime.
Setter methods: PreparedStatement providing setter methods by which we can set values to
query parameters.
public void setInt(int paramIndex, int value) Sets int value to parameter
public void setString(int paramIndex, String value) Sets string value to parameter
public void setFloat(int paramIndex, float value) Sets float value to parameter
public void setDouble(int paramIndex, double value) Sets double value to parameter
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 14
Inserting new record into Account table:
import java.sql.*;
public class InsertRecord
{
public static void main(String args[]) throws Exception
{
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 15
Insert records by reading input using Scanner class:
import java.sql.*;
import java.util.Scanner;
public class InsertRecord
{
public static void main(String args[]) throws Exception
{
Connection conn = null;
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
ps.setInt(1, num);
ps.setString(2, name);
ps.setInt(3, balance);
int count = ps.executeUpdate();
System.out.println("Records updated : " + count);
}
finally
{
if(conn != null){
conn.close();
System.out.println("Connection closed");
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 16
Update Record through User Input
Update record using preparedStatement:
• We read the input from the user to update the data.
• PrepareStatement object is used for data updation.
• executeUpdate() method must be called for this updation.
import java.sql.*;
import java.util.Scanner;
public class RecordUpdate
{
static Connection con;
public static void main(String args[]) throws Exception
{
Scanner scan = new Scanner(System.in);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String cs=" jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(cs, "system", "admin");
System.out.print("Enter account number : ");
int acc = scan.nextInt();
System.out.print("Enter deposit amount : ");
int amt = scan.nextInt();
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 17
Insert Record by reading account details using BufferedReader:
• BufferedReader class belongs to IO package.
• BufferedReader class is providing readLine() method by which we can read input values.
• readLine() method returns input in String format only.
import java.io.*;
import java.sql.*;
public class PreparedInsertRecord
{
static Connection con;
static BufferedReader br;
public static void main(String args[]) throws Exception
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver is ready");
con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:xe", "system", "admin");
System.out.println("Connection is ready");
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter account details(num, name, balance : ");
int nu = Integer.parseInt(br.readLine());
String na = br.readLine();
int ba = Integer.parseInt(br.readLine());
String query = "insert into account values(?,?,?)";
PreparedStatement stmt=con.prepareStatement(query);
stmt.setInt(1, nu);
stmt.setString(2, na);
stmt.setInt(3, ba);
int count = stmt.executeUpdate();
System.out.println("Updated record(s) : " + count);
}
finally{
if(con != null)
con.close();
if(br != null)
br.close();
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 18
Batch Processing in JDBC
It is the concept of submitting group of related SQL statements with one call to database.
It improves the performance by reduce the amount of communication.
Statement interface providing methods for batch processing.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 19
Batch processing using PreparedStatement example:
import java.io.*;
import java.sql.*;
public class BatchPrepared
{
static Connection con;
static BufferedReader br;
public static void main(String args[]) throws Exception{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String cs = "jdbc:oracle:thin:@localhost:1521:xe";
con = DriverManager.getConnection(cs, "system", "admin");
System.out.println("Connection is ready");
br = new BufferedReader(new InputStreamReader(System.in));
String query = "insert into account values(?,?,?)";
PreparedStatement stmt=con.prepareStatement(query);
while(true)
{
System.out.println("Enter accdetails(num, name, balance) : ");
int nu = Integer.parseInt(br.readLine());
String na = br.readLine();
int ba = Integer.parseInt(br.readLine());
stmt.setInt(1, nu);
stmt.setString(2, na);
stmt.setInt(3, ba);
stmt.addBatch();
System.out.println("Query added to batch");
System.out.println("Do you add one more record(y/n) : ");
if(br.readLine().charAt(0)=='n')
break;
}
stmt.executeBatch();
System.out.println("Batch executed");
}
finally{
if(con != null)
con.close();
if(br != null)
br.close();
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 20
JDBC – CRUD – Account Operations
Create Account table in Oracle Database:
create table account(num int, name varchar2(20), balance int);
Menu Driven CRUD example to perform Account operations such as create account, delete
account, update account, and withdraw from account and deposit:
package ameerpet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class AccountOperations
{
static Scanner scan = new Scanner(System.in);
static private String driver = "oracle.jdbc.driver.OracleDriver";
static private String url = "jdbc:oracle:thin:@localhost:1521:XE";
static Connection con=null;
public static void main(String[] args)
{
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, "system", "admin");
while(true)
{
System.out.println("Account Opereations");
System.out.println("1. Create Account");
System.out.println("2. Display Account details");
System.out.println("3. Deposit");
System.out.println("4. Withdraw");
System.out.println("5. Money Transfer");
System.out.println("6. Delete Account");
System.out.println("7. Quit");
if(ch==1)
createAccount();
else if(ch==2)
displayDetails();
else if(ch==3)
deposit();
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 21
else if(ch==4)
withdraw();
else if(ch==5)
moneyTransfer();
else if(ch==6)
deleteAccount();
else if(ch==7){
System.out.println("End of operations");
break;
}
else
System.out.println("Error : Invalid choice");
}
}
catch(Exception e){
System.out.println("Exception : " + e.getMessage());
}
finally{
if(con != null){
try {
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 22
static void displayDetails() throws SQLException
{
System.out.println("Enter account num : ");
int num = scan.nextInt();
String query = "select * from account where num=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
ResultSet rs = ps.executeQuery();
if(rs.next()){
String name = rs.getString(2);
int balance = rs.getInt(3);
System.out.println("Details : " + num + " , " + name + " , " + balance);
}
else
System.out.println("Error : Invalid Account number");
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 23
if(rs.next())
{
int balance = rs.getInt(1);
if(amt <= balance)
{
System.out.println("Collect cash : " + amt);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 24
Callable Statement – Execute Stored Procedures
CallableStatement interface:
• The interface used to call stored procedures and functions.
• SQL stored procedures and functions are used to write and store business logic inside
A
the database.
M
Stored Procedure: E
• Stored procedure is a named PL/SQL block.
• Stored procedure stores in the database only. E
• To execute stored procedure, we must call like function. R
• A stored procedure consists of a series of SQL and PL/SQL statements that perform a
specific task. P
E
How to get the instance of CallableStatement?
T
• The prepareCall() method of Connection interface returns the instance of
CallableStatement.
o CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}"); T
E
Create Table:
create table account(num int not null unique, name varchar(20), balance int); C
H
Inserting records:
insert into account values(101, 'Amar', 5000); N
insert into account values(102, 'Annie', 6000);
commit; O
L
Example1: Stored procedure in Oracle that inserts data into an account table with columns
num, name, and balance: O
G
Procedure:
CREATE OR REPLACE PROCEDURE insert_account( I
num IN NUMBER, E
name IN VARCHAR2,
balance IN NUMBER S
) AS
BEGIN
INSERT INTO account values (num, name, balance);
COMMIT;
END;
/
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 25
JDBC Callable Statement example to insert record into account table:
import java.sql.*;
import java.util.Scanner;
public class CallableInsert
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String cs = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = DriverManager.getConnection(cs, "system", "admin");
cstmt.setInt(1, num);
cstmt.setString(2, name);
cstmt.setDouble(3, balance);
cstmt.execute();
System.out.println("Account inserted successfully.");
conn.close();
}
catch (Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 26
Stored Procedure to check the balance is present or not in Database table:
CREATE OR REPLACE PROCEDURE check_amount(
p_account_num IN NUMBER,
p_amount IN NUMBER,
p_result OUT VARCHAR2
) AS
v_balance NUMBER;
BEGIN
SELECT balance INTO v_balance
FROM account
WHERE num = p_account_num;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 27
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.execute();
Stored procedure in Oracle that allows withdrawing an amount from an account table by
checking if there is sufficient balance:
CREATE OR REPLACE PROCEDURE withdraw_amount(
p_account_num IN NUMBER,
p_amount IN NUMBER,
p_result OUT VARCHAR2
) AS
v_balance NUMBER;
BEGIN
-- Retrieve the current balance
SELECT balance INTO v_balance
FROM account
WHERE num = p_account_num;
COMMIT;
p_result := 'Amount withdrawn successfully.';
ELSE
p_result := 'Insufficient balance. Withdrawal failed.';
END IF;
END;
/
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 28
Callable Statement Program:
import java.sql.*;
import java.util.Scanner;
public class CallableWithdraw
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String cs = "jdbc:oracle:thin:@localhost:1521:xe";
Connection conn = DriverManager.getConnection(cs, "system", "admin");
cstmt.setInt(1, accountNum);
cstmt.setInt(2, amount);
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.execute();
conn.close();
}
catch (Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 29
JDBC - Transactions
Transaction Management: The sequence of actions (SQL statements) is treated as a single unit
that is known as a transaction.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 30
Transfer amount from one account to another account:
• In this program, we start by getting the source account number, destination account
number, and transfer amount from the user.
• Then, we execute two SELECT statements to retrieve the balances of the source and
destination accounts.
• We check if the source account has sufficient balance to transfer the amount, and if not,
we exit the program.
• Next, we use two UPDATE statements to update the balances of the source and
destination accounts.
• If any of the UPDATE statements fail to update any rows, we roll back the transaction and
exit the program.
• Otherwise, we commit the transaction and print a success message.
Program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class TransferAmount
{
public static void main(String[] args)
{
String driver = "oracle.jdbc.driver.OracleDriver";
try
{
Class.forName(driver);
System.out.println("Driver loaded");
String cs = "jdbc:oracle:thin:@localhost:1521:XE";
Connection con = DriverManager.getConnection(cs, "system", "admin");
System.out.println("Connection is ready");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 31
System.out.println("Enter Acc Num from which transfer amount : ");
int src = scan.nextInt();
con.setAutoCommit(false);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 32
}
}
else
{
System.out.println("Error : Insufficient funds in source account");
}
}
else
{
System.out.println("Error : Source account number is not valid");
}
con.close();
}
catch(Exception e)
{
System.out.println("Exception : " + e.getMessage());
}
}
}
Output:
Driver loaded
Connection is ready
Enter Acc Num from which transfer amount :
103
Enter Amount to Transfer :
3000
Enter Acc Num to which transfer amount :
101
Amount deducted from source account
Amount transfered successfully
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 33
Servlets
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 34
Servlets
Introduction to Servlets:
• Servlets are used to develop server side applications.
• Servlet is a java class that runs from server.
• Servlets run inside a web server and can receive and respond to HTTP requests. A
• Java Servlet API, which is a set of interfaces and classes.
M
• Servlets are server-side components that are used to create dynamic web pages.
E
HttpServlet: E
• The HTTP Servlet class handles HTTP requests and responses.
R
• The HTTP Servlet class is an abstract class that must be subclassed to be used.
• Subclasses of the HTTP Servlet class implement the methods that handle HTTP requests P
and responses. E
• The two most important methods that need to be implemented are the "doGet" and
T
"doPost" methods.
• The "doGet" method handles HTTP GET requests, which are typically used to retrieve
data from a server. The "doPost" method handles HTTP POST requests, which are T
typically used to submit data to a server. E
C
Servlet Life Cycle: The Servlet life cycle refers to the sequence of steps that occur during the
creation, initialization, execution, and destruction of a Servlet. H
N
1. Loading: Web server loads the Servlet class file into memory.
O
2. Instantiation: Servlet container creates an instance of the Servlet class using zero args L
constructor.
O
3. Initialization: Servlet container initializes it by calling its "init" method. This method G
reading configuration parameters or connecting to a database. I
4. Servicing the Request: Servlet is ready to handle client requests such as "doGet" or E
"doPost", to service the request. S
5. Destroying the Servlet: When the web server is shut down, the Servlet container calls
the "destroy" method of the Servlet to perform any necessary cleanup tasks, such as
closing database connections or releasing resources.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 35
Program to understand Servlet Life Cycle:
import javax.servlet.*;
import java.io.*;
public class ExampleServlet implements Servlet
{
public ExampleServlet()
{
System.out.println("Servlet instantiated.");
}
@Override
public void init(ServletConfig config) throws ServletException
{
System.out.println("Servlet initialized.");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
System.out.println("Servicing the request.");
}
@Override
public void destroy()
{
System.out.println("Servlet destroyed.");
}
@Override
public ServletConfig getServletConfig()
{
return null;
}
@Override
public String getServletInfo()
{
return null;
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 36
XML File in Web App Development
Web.xml file:
• The web.xml file is a deployment descriptor for a Java web application.
• In Servlets, the web.xml file maps servlets to URLs, and specifies initialization parameters.
• It also defines the filters and listeners used in the application.
Here are some of the important roles that the web.xml file plays in a Servlet-based web
application:
Defines servlets: The web.xml file defines the servlets that are used in the application, including
their class names and URL mappings.
Configures servlets: The web.xml file specifies the initialization parameters for each servlet,
such as database connection parameters and other configuration settings.
Maps URLs to servlets: The web.xml file maps URLs to servlets, which enables the application
to respond to incoming HTTP requests.
Configures filters: The web.xml file defines filters used in the application, which are used to
perform tasks such as authentication, logging, and input validation.
Configures listeners: The web.xml file also defines listeners used in the application, which are
used to respond to various events in the application lifecycle, such as when the application starts
or stops.
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<context-param>
<param-name>db.url</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</context-param>
</web-app>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 37
Read Input from HTML form and display on web page:
index.html:
<!DOCTYPE html>
<html>
<body>
<form action="GreetServlet" method="get">
Enter your name : <input type="text" name="nm"/>
<input type="submit" value="Show Greet"/>
</form>
</body>
</html>
GreetServlet.java:
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("/GreetServlet")
public class GreetServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name = request.getParameter("nm");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 38
Config and Context Parameters in Servlets
In Servlets, there are two types of parameters that can be configured for a web application:
Config parameters and Context parameters.
Config:
• Config parameters are specific to individual Servlets.
• Config parameters defined within the Servlet's configuration in the web.xml file.
• Config parameters are retrieved using the ServletConfig object.
• Some common examples of config parameters include database connection details and
file paths.
Context:
• Context parameters, on the other hand, are global to the entire web application.
• Context parameters are defined in the web.xml file using the <context-param> element.
• They are used to provide configuration information that is shared across all Servlets and
are retrieved using the ServletContext object.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
<init-param>
<param-name>message</param-name>
<param-value>Hello, World!</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
</web-app>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 39
Collect Config and Context Parameters in Servlets:
package com.example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet
{
private String message;
private String dbUrl;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 40
Read Details from HTML form and Insert into Database
<tr>
<td> Enter Name : </td>
<td> <input type="text" name="name"/>
</tr>
<tr>
<td> Enter Balance : </td>
<td> <input type="text" name="balance"/>
</tr>
<tr>
<td colspan="2"> <input type="submit"
value="Insert"/>
</tr>
</table>
</form>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 41
InsertServlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/InsertRecord")
public class InsertRecord extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection con = null;
try
{
int num = Integer.parseInt(request.getParameter("num"));
String name = request.getParameter("name");
int balance = Integer.parseInt(request.getParameter("balance"));
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String uname = "system";
String pwd = "admin";
con = DriverManager.getConnection(url, uname, pwd);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 42
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 43
Application Display the details of Specified record
Check the table details: Checking the details of records once before retrieving the data.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Display Record</title>
</head>
<body>
<form action="DisplayRecord" method="get">
<table>
<caption> Enter account number </caption>
<tr>
<td> Enter Number : </td>
<td> <input type="text" name="num"/>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Get Info"/>
</tr>
</table>
</form>
</body>
</html>
DisplayRecord.java:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/DisplayRecord")
public class DisplayRecord extends HttpServlet
{
private static final long serialVersionUID = 1L;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 44
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection con = null;
try
{
int num = Integer.parseInt(request.getParameter("num"));
Class.forName("oracle.jdbc.driver.OracleDriver");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 45
con.close();
} catch (SQLException e) {
}
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 46
Display all records of Account table
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/DisplayRecord")
public class DisplayTable extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection con = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 47
pw.print("<html> " + "<body> "
+ "<table border='1'>");
while(rs.next())
{
pw.print("<tr>"
+ "<td>" + rs.getInt(1) + "</td>"
+ "<td>" + rs.getString(2) + "</td>"
+ "<td>" + rs.getInt(3) + "</td>"
+ "</tr>");
}
pw.print("<table>"
+ "</body> "
+ "</html>"
);
}
else
{
pw.print("<h1> No records in Account table </h1>");
}
}
catch(Exception e)
{
pw.println("<h1> Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(con != null)
{
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 48
Form Validation before submit details to Server
index.html:
• onsubmit attribute is used to validate the form before submit.
• If the true value returned from the form then the data submit to server.
<!DOCTYPE html>
<html>
<head>
<title>Insert Record</title>
<script>
function validate()
{
var s1 = document.insert.num.value ;
var s2 = document.insert.name.value ;
var s3 = document.insert.balance.value ;
if(s1.length > 0 && s2.length>0 && s3.length>0){
return true;
}
else {
alert("pls enter data before submit");
return false;
}
}
</script>
</head>
<body>
<form name = "insert" action="InsertRecord" method="post"
onsubmit="return validate()">
<table>
<caption> Enter Account Details </caption>
<tr>
<td> Enter Number : </td>
<td> <input type="text" name="num"/>
</tr>
<tr>
<td> Enter Name : </td>
<td> <input type="text" name="name"/>
</tr>
<tr>
<td> Enter Balance : </td>
<td> <input type="text" name="balance"/>
</tr>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 49
<tr>
<td colspan="2"> <input type="submit" value="Insert"/>
</tr>
</table>
</form>
</body>
</html>
InsertServlet.java:
import java.io.*;
import java.sql.*;
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("/InsertRecord")
public class InsertRecord extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection con = null;
try
{
int num = Integer.parseInt(request.getParameter("num"));
String name = request.getParameter("name");
int balance = Integer.parseInt(request.getParameter("balance"));
Class.forName("oracle.jdbc.driver.OracleDriver");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 50
ps.setString(2, name);
ps.setInt(3, balance);
ps.executeUpdate();
pw.print("<h1> Record inserted successfully </h1>");
}
catch(Exception e)
{
pw.println("<h1> Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(con != null)
{
try {
con.close();
} catch (SQLException e) { }
}
}
}
}
Output:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 51
Update Account Name by getting the details
E
Step2 : If the account number is invalid, raise the error message and give link to E
index.html to re-enter the account number.
R
Step3 : If the account number is valid, display details to modify the new account name.
T
L
Step4: Update the details after modify
O
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 52
Index.html:
<!DOCTYPE html>
<html>
<head>
<title>Display Record</title>
</head>
<body>
<form action="DisplayRecord" method="get" onsubmit="return validate()">
<table>
<caption> Enter account number </caption>
<tr>
<td> Enter Number : </td>
<td> <input type="text" name="num"/>
</tr>
<tr>
<td colspan="2"> <input type="submit" value="Get
Info"/>
</tr>
</table>
</form>
</body>
</html>
DisplayRecord.java:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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("/DisplayRecord")
public class DisplayRecord extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 53
Connection con = null;
try
{
int num = Integer.parseInt(request.getParameter("num"));
Class.forName("oracle.jdbc.driver.OracleDriver");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 54
catch(Exception e)
{
pw.println("<h1> Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(con != null)
{
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
UpdateRecord.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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/UpdateRecord")
public class UpdateRecord extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection con = null;
try
{
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 55
int num = Integer.parseInt(request.getParameter("num"));
String name = request.getParameter("name");
Class.forName("oracle.jdbc.driver.OracleDriver");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 56
Servlet RequestDispatcher
forward(): The forward() method of the RequestDispatcher interface allows you to forward a
request from a Servlet or JSP to another Servlet, JSP, or HTML page on the server-side.
include(): The include() method of the RequestDispatcher interface allows you to include the
response generated by another resource (e.g., Servlet, JSP) into the response of the current
Servlet or JSP.
Login Application:
• The following Login application explains clearly about forward() and include() methods.
• If the Login success, then the request forwarded to WelcomeServlet and the
WelcomeServlet generate the output.
• If the Validation fails then the index.html page included by the same servlet.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 57
login.html:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form method="post" action="ValidateServlet">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value="Login" />
</form>
</body>
</html>
ValidateServlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ValidateServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("admin123"))
{
RequestDispatcher dispatcher = request.getRequestDispatcher("WelcomeServlet");
dispatcher.forward(request, response);
}
else
{
String message = "Invalid username or password!";
request.setAttribute("message", message);
RequestDispatcher dispatcher = request.getRequestDispatcher("login.html");
dispatcher.include(request, response);
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 58
WelcomeServlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException A
{ M
PrintWriter out = response.getWriter();
out.println("<html><head><title>Welcome Page</title></head><body>"); E
out.println("<h1>Welcome " + request.getParameter("username") + "!</h1>"); E
out.println("</body></html>");
} R
} P
SendRedirect E
T
forward() v/s sendRedirect(): The forward() and sendRedirect() methods are both used for
redirecting a request from one servlet to another resource.
T
Request vs Response: The forward() method is used to forward the request from one servlet to
another servlet, while the sendRedirect() method sends a new request to client and then E
redirects it to another resource.
C
URL Changes: The forward() method does not change the URL in the browser's address bar, H
while the sendRedirect() method changes the URL to the new resource.
N
Request and Response Objects: When using forward(), the original request and response O
objects are forwarded to the new resource however, when using sendRedirect(), a new request
L
and response objects are created.
O
Performance: Since forward() does not create a new request/response object, it is faster and
G
more efficient than sendRedirect(), which creates a new request/response object.
I
Restrictions: When using forward(), the new resource must be on the same server and in the
E
same web application where as sendRedirect(), the new resource can be on a different server or
a different web application. S
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 59
Session Management
• Session management is an essential feature of web applications that allows tracking and
managing the state of user interactions.
• Servlets provide built-in support for session management using the HttpSession API.
Creating a Session:
• To create a new session, you can call the getSession() method on the HttpServletRequest
object.
• This method returns the current session associated with this request, or creates a new
session if one does not exist.
HttpSession session = request.getSession();
Invalidating a Session:
• When a user logs out or the session expires, you may want to invalidate the session to
release any resources associated with it.
• To invalidate a session, you can call the invalidate() method on the HttpSession object.
session.invalidate();
Session Timeout:
• By default, a session lasts until the user closes their browser or logs out.
• However, you can set a timeout for the session using the setMaxInactiveInterval()
method. This method takes an integer value in seconds.
session.setMaxInactiveInterval(1800); // set the session timeout to 30 minutes
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 60
Login and Logout Application with Session Management
login.html:
<!DOCTYPE html>
<html>
<head><title>Login</title></head>
<body>
<h1>Login</h1>
<form action="LoginServlet" method="post">
<label>Username:</label>
<input type="text" name="username"><br><br>
<label>Password:</label>
<input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
LoginServlet.java:
package online;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("amar") && password.equals("1234"))
{
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("logout.jsp");
}
else
{
request.setAttribute("message", "Invalid username or password");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 61
RequestDispatcher dispatcher =
request.getRequestDispatcher("login.html");
dispatcher.include(request, response);
}
}
}
logout.jsp:
<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body>
<h1>Welcome</h1>
<p>You are logged in as <%= session.getAttribute("username") %>.</p>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout">
</form>
</body>
</html>
LogoutServlet.jsp:
package online;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
HttpSession session = request.getSession(false);
if (session != null)
{
session.invalidate();
}
response.sendRedirect("login.html");
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 62
Banking Project – Code
Login Page:
Registration Page:
Services Page:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 63
Source Code
Login.html:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to Banking</h1>
<form action="LoginServlet" method="POST">
Enter UserName : <input type="text" name="username" required><br/>
Enter Password : <input type="password" id="password" name="password" required><br/>
<input type="submit" value="Login">
</form>
<p>If you haven't registered yet, <a href="Register.html">click here</a> to register.</p>
</body>
</html>
Register.html:
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script>
function validateForm()
{
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmPassword").value;
RegisterServlet.java:
package bank;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 64
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static String driver = "oracle.jdbc.driver.OracleDriver";
static String url = "jdbc:oracle:thin:@localhost:1521:XE";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, "system", "admin");
String sql = "INSERT INTO login (username, password) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int count = stmt.executeUpdate();
response.setContentType("text/html");
if(count>0){
out.println("<h1>Registration Success, Please Login Now</h1>");
RequestDispatcher rd = request.getRequestDispatcher("Login.html");
rd.include(request, response);
}
else{
out.println("<h1>Registration Failed, Try Again</h1>");
RequestDispatcher rd = request.getRequestDispatcher("Registration.html");
rd.include(request, response);
}
}
catch(Exception e){
out.println("<h1>Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 65
LoginServlet.java:
package bank;
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 javax.servlet.RequestDispatcher;
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("/LoginServlet")
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static String driver = "oracle.jdbc.driver.OracleDriver";
static String url = "jdbc:oracle:thin:@localhost:1521:XE";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, "system", "admin");
String sql = "SELECT * FROM login WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
response.setContentType("text/html");
if (rs.next())
{
out.println("<h1>Hello " + username + ", Welcome to Banking Services</h1>");
HttpSession session = request.getSession();
session.setAttribute("username", username);
RequestDispatcher rd = request.getRequestDispatcher("Services.html");
rd.include(request, response);
}
else
{
out.println("<h1>Login Failed, Please Login Again</h1>");
RequestDispatcher rd = request.getRequestDispatcher("Login.html");
rd.include(request, response);
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 66
catch(Exception e)
{
out.println("<h1>Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(conn != null)
{
try{
conn.close();
}
catch (SQLException e){
e.printStackTrace();
}
}
}
}
}
Services.html:
<!DOCTYPE html>
<html>
<head>
<title>Services</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
nav {
background-color: green;
color: white;
padding: 10px;
}
nav ul {
margin: 0;
padding: 0;
list-style-type: none;
text-align: center;
}
nav ul li {
display: inline-block;
margin-right: 20px;
}
nav ul li a {
color: #fff;
text-decoration: none;
padding: 5px 10px;
border-radius: 3px;
}
nav ul li a:hover {
background-color: #555;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 67
}
form {
display: none;
width: 300px;
margin: 20px auto;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"],
input[type="number"],
input[type="submit"] {
width: 100%;
padding: 5px;
margin-bottom: 10px;
}
</style>
<script>
function showForm(formId) {
var forms = document.getElementsByTagName("form");
for (var i = 0; i < forms.length; i++) {
forms[i].style.display = "none";
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 68
<form id="withdraw_form" action="WithdrawServlet" method="post" style="display: none;">
<h2>Withdraw</h2>
Enter Account num : <input type="text" id="accountNumberWithdraw"
name="accountNumberWithdraw" required>
Enter Withdraw amt : <input type="number" id="amountWithdraw"
name="amountWithdraw" required>
<input type="submit" value="Withdraw">
</form>
AccountCreationServlet.java
package bank;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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("/AccountCreationServlet")
public class AccountCreationServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static String driver = "oracle.jdbc.driver.OracleDriver";
static String url = "jdbc:oracle:thin:@localhost:1521:XE";
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 69
stmt.setString(2, name);
stmt.setInt(3, balance);
int count = stmt.executeUpdate();
response.setContentType("text/html");
if(count>0){
out.println("<h1>Account Created Successfully</h1>");
RequestDispatcher rd = request.getRequestDispatcher("Services.html");
rd.include(request, response);
}
else{
out.println("<h1>Account Creation Failed, Try Again</h1>");
RequestDispatcher rd = request.getRequestDispatcher("Services.html");
rd.include(request, response);
}
}
catch(Exception e){
out.println("<h1>Exception : " + e.getMessage() + "</h1>");
}
finally{
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
LogoutServlet.java:
package bank;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet
{
if (session != null) {
session.invalidate();
}
response.sendRedirect("Login.html");
}
}
Complete the remaining services logic like above to complete the project
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 70
JSP
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 71
JSP Tutorial
Servlet JSP
Servlets run faster than JSP. JSP runs slower than servlet as it takes time to
compile the program and convert into servlets.
It is hard to write code in servlet. It’s easier to code in JSP compared to servlets.
In MVC architecture, servlet works as a In MVC architecture, JSP works as a view for
controller. displaying output.
There is no custom tag writing facility in You can easily build custom tags that can
servlets. directly call Java beans.
Servlet is a java code. JSP is a HTML-based code.
In Servlet, you have to implement both In JSP, business logic is split from presentation
business logic and presentation logic in logic using JavaBeans.
the single file.
Scriptlet tags:
• These tags allow you to write Java code that will be executed when the JSP page is
loaded.
• Scriptlet tags are surrounded by <% and %> symbols.
<%
String name = "Alice";
int age = 30;
out.println(name);
%>
Expression tags:
• These tags allow you to evaluate a Java expression and print its value in the HTML
output.
• Expression tags are surrounded by <%= and %> symbols.
Declaration tags:
• These tags allow you to declare Java methods and variables that can be used throughout
the JSP page.
• Declaration tags are surrounded by <%! and %> symbols.
<%!
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 72
public int multiply(int a, int b) {
return a * b;
}
%>
<%
int x = 3;
int y = 4;
int result = multiply(x, y);
%>
<p>The result of <%= x %> times <%= y %> is <%= result %>.</p>
Insert.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Form</title>
</head>
<body>
<form action="InsertRecord.jsp" method="post">
Enter Emp ID : <input type="text" name="num"/>
<br/>
Enter Emp Name : <input type="text" name="name"/>
<br/>
Enter Emp Salary : <input type="text" name="sal"/>
<br/>
<input type="submit" value="Insert">
</form>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 73
InsertRecord.jsp:
<%@ page import="java.sql.*" %>
<%
String id = request.getParameter("num");
String name = request.getParameter("name");
String salary = request.getParameter("sal");
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
conn.close();
out.println(rowsInserted + " row(s) inserted into the employees table.");
}
catch (ClassNotFoundException e)
{
out.println("Error: " + e.getMessage());
}
catch (SQLException e)
{
out.println("Error: " + e.getMessage());
}
%>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 74
Retrieve Employee Details
Retrieve.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<h1>Employee Details</h1>
<form action="GetInfo.jsp" method="GET">
<label>Enter Employee ID:</label>
<input type="text" name="num">
<br><br>
<input type="submit" value="Get Info">
</form>
</body>
</html>
GetInfo.jsp:
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Get Account Details</title>
</head>
<body>
<%
int num = Integer.parseInt(request.getParameter("num"));
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "admin");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 75
if (rs.next())
{
String name = rs.getString("name");
int salary = rs.getInt("salary");
out.println("<h1>Employee Details</h1>");
out.println("<p>Emp ID is : " + num + "</p>");
out.println("<p>Emp Name is : " + name + "</p>");
out.println("<p>Emp Salary is : " + salary + "</p>");
}
else
{
out.println("<h1>Record not found</h1>");
}
rs.close();
pstmt.close();
conn.close();
%>
</body>
</html>
TableData.jsp:
<%@ page import="java.sql.*" %>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 76
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String username = "system";
String password = "admin";
con = DriverManager.getConnection(url, username, password);
stmt = con.createStatement();
String sql = "SELECT * FROM employee";
rs = stmt.executeQuery(sql);
out.println("<table>");
out.println("<tr><th>ID</th><th>Name</th><th>Salary</th></tr>");
while (rs.next())
{
int empId = rs.getInt("id");
String empName = rs.getString("name");
int empSalary = rs.getInt("salary");
out.println("<tr>");
out.println("<td>" + empId + "</td>");
out.println("<td>" + empName + "</td>");
out.println("<td>" + empSalary + "</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
}
%>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 77
Request Dispatcher – forward() and include()
Request Dispatcher:
• RequestDispatcher is an interface in the Java Servlet API.
• It provides a way to forward requests from one servlet/JSP to another servlet/JSP.
• It also provides how to include the content of one servlet/JSP in another servlet/JSP.
• We get RequestDispatcher object by calling the getRequestDispatcher() method on
HttpServletRequest object.
• The getRequestDispatcher() method takes a string input that represents the URL or path
of the servlet/JSP to which the request is to be forwarded.
• The included content of one servlet/JSP into another can be done by calling the include()
method of the RequestDispatcher interface.
• The include() method takes the request and response objects as arguments.
login.jsp:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="authentication.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password"
name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
authentication.jsp:
<%@ page import="java.util.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 78
}
else
{
out.println("Invalid username or password. Please try again.");
}
%>
welcome.jsp:
<%@ page import="java.util.*" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<%
String username = (String) session.getAttribute("username");
out.println("Welcome, " + username + "!");
%>
</body>
</html>
include() example
login.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<% String error = (String) request.getAttribute("error"); %>
<% if (error != null) { %>
<p><%= error %></p>
<% } %>
<form action="authentication.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password"
name="password"><br><br>
<input type="submit" value="Login">
</form>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 79
</body>
</html>
authentication.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
welcome.jsp:
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<%
String username = (String) session.getAttribute("username");
out.println("Welcome, " + username + "!");
%>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 80
Send Re-direct
index.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to my website</h1>
<p>Click the button below to go to the redirect page.</p>
<form method="get" action="RedirectServlet">
<input type="submit" value="Go to Redirect Page">
</form>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 81
RedirectServlet.java:
import java.io.IOException;
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("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
redirect.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Redirect Page</title>
</head>
<body>
<h1>You have been redirected to this page!</h1>
<p>Click the button below to go back to the home page.</p>
<form method="get" action="index.jsp">
<input type="submit" value="Go to Home Page">
</form>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 82
Login – Logout Session Example
HTTPSession:
• HTTP session is a way to maintain state across multiple HTTP requests between a client
and a server.
• When a new session is created, a unique session ID is generated and sent to the client.
• In JSP, you can access the HTTP session using the session object.
• You can store data in the session using the setAttribute() method.
• You can retrieve data from the session using the getAttribute() method.
• Session data is stored on the server side, so it is secure and cannot be tampered with by
the client.
• By default, the session expires when the user closes the browser or after a certain period
of inactivity.
• You can also configure the session timeout period in the web application deployment
descriptor (web.xml) or programmatically using the setMaxInactiveInterval() method.
• You can invalidate a session using the invalidate() method, which removes all the
attributes and data associated with the session.
login.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Login</title></head>
<body>
<h1>Login</h1>
<%-- Display an error message if provided --%>
<% String error = (String) request.getAttribute("error"); %>
<% if (error != null) { %>
<p class="error"><%= error %></p>
<% } %>
<form action="authentication.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
authentication.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.io.PrintWriter" %>
<%
String username = request.getParameter("username");
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 83
String password = request.getParameter("password");
if (username.equals("admin") && password.equals("password")){
session.setAttribute("username", username);
response.sendRedirect("services.jsp");
}
else{
String error = "Invalid username or password. Please try again.";
request.setAttribute("error", error);
request.getRequestDispatcher("login.jsp").forward(request, response);
}
%>
services.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head><title>Services</title></head>
<body>
<% String username = (String) session.getAttribute("username"); %>
<h1>Welcome, <%= username %>!</h1>
<h2>Menu</h2>
<ul>
<li><a href="services.jsp">Home</a></li>
<li><a href="services.jsp?page=profile">Profile</a></li>
<li><a href="services.jsp?page=settings">Settings</a></li>
<li><a href="logout.jsp">Logout</a></li>
</ul>
</body>
</html>
logout.jsp:
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Logout</title>
</head>
<body>
<% session.invalidate(); %>
<h2>Logged out successfully!</h2>
<p><a href="login.jsp">Click here</a> to login again.</p>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 84
MVC Flow with Servlets - JSP
Model: The model represents the data and business logic of the application.
View: The view is responsible for presenting the data to the user.
Controller: The controller acts as an intermediary between the model and the view.
Separation of concerns: MVC promotes a separation of concerns, where each component has a
specific role and responsibility.
Flexibility and reusability: MVC enables flexibility and reusability in software development.
DAO is a design pattern that is commonly used to separate application and the data source,
such as a database.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 85
getInfo.jsp:
<html>
<head>
<title>Get Account Info</title>
</head>
<body>
<h1>Get Account Information</h1>
<form action="ControllerServlet" method="get">
Enter Account Num : <input type="text" name="num" required/>
<input type="submit" value="Get Info">
</form>
</body>
</html>
Account.java:
package com.example;
public class Account
{
private int num;
private String name;
private int balance;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 86
ControllerServlet.java:
package com.example;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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("/ControllerServlet")
public class ControllerServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
int num = Integer.parseInt(request.getParameter("num"));
Account acc = new Account();
acc.setNum(num);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 87
AccountDAO.java
package com.example;
import java.sql.*;
public class AccountDAO{
private static Connection con;
private static String url = "jdbc:oracle:thin:@localhost:1521:xe";
private static String username = "system";
private static String password = "admin";
public boolean getData(Account acc){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, username, password);
int num = acc.getNum();
String query = "SELECT * FROM account WHERE num = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
ResultSet rs = ps.executeQuery();
if(rs.next()){
String name = rs.getString(2);
int balance = rs.getInt(3);
acc.setName(name);
acc.setBalance(balance);
return true;
}
else
return false;
}
catch (Exception e){
return false;
}
finally{
if(con != null){
try {
con.close();
}
catch (SQLException e) {
System.out.println("Error : " + e.getMessage());
}
}
}
}
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 88
view.jsp:
<%@ page import="com.example.Account" %>
<html>
<head>
<title>Account Information</title>
</head>
<body>
<h1>Account Information</h1>
<%-- Retrieve account object from request --%>
<%
Account account = (Account) request.getAttribute("account");
%>
<table>
<tr>
<th>Account Number</th>
<th>Account Name</th>
<th>Balance</th>
</tr>
<tr>
<td><%= account.getNum() %></td>
<td><%= account.getName() %></td>
<td><%= account.getBalance() %></td>
</tr>
</table>
</body>
</html>
error.jsp:
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p>The account does not exist.</p>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 89
JSTL - JSP
JSTL Tags: JavaServer Pages Standard Tag Library (JSTL) Core tags provide a set of useful tags
for performing common tasks in JSP pages.
<c:choose> - It is used for selecting one of several blocks of code based on conditions.
<c:choose>
<c:when test="${user.isAdmin}">
<!-- Admin content -->
</c:when>
<c:otherwise>
<!-- Regular user content -->
</c:otherwise>
</c:choose>
<c:forEach> - It is used for iterating over collections, arrays, or other iterable objects.
<c:forEach items="${products}" var="product">
<!-- Display each product -->
${product.name}
</c:forEach>
<c:url> - This tag is used for encoding URLs to ensure proper formatting.
<a href="<c:url value='/products?id=1' />">Product 1</a>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 90
<c:param> - This tag is used to add parameters to URLs.
<c:url var="productUrl" value="/product.jsp">
<c:param name="id" value="123" />
</c:url>
<a href="${productUrl}">Product Details</a>
CRUD Application
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 91
index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<h1 style="color:red">JSP CRUD APPLICATION FOR USER</h1>
<a href="addUserForm.jsp">Add User</a>
<a href="viewusers.jsp">View Users</a>
</body>
</html>
addUserForm.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<jsp:include page="userForm.html"></jsp:include>
</body>
</html>
userForm.html:
<html>
<body>
<a href="viewusers.jsp">View All Records</a><br/>
<h1>Add New User</h1>
<form action="addUser.jsp" method="post">
<table>
<tr>
<td>ID:</td>
<td><input type="text" name="id"/></td>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 92
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" name="email"/></td>
</tr>
<tr>
<td>Sex:</td>
<td><input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td>
</tr>
<tr>
<td>Country:</td>
<td>
<select name="country" style="width:155px">
<option>India</option>
<option>USA</option>
<option>UK</option>
<option>Canada</option>
<option>Other</option>
</select>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Add User"/></td>
</tr>
</table>
</form>
</body>
</html>
addUser.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="com.dao.UserDAO"%>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 93
<jsp:useBean id="user" class="com.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="user"/>
<%
int i=UserDAO.save(user);
if(i>0){
response.sendRedirect("adduser-success.jsp");
}
else{
response.sendRedirect("adduser-error.jsp");
}
%>
com.bean.User.java:
package com.bean;
public class User
{
private int id;
private String name, password, email, sex, country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 94
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
com.dao.UserDAO.java:
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.bean.User;
public class UserDAO
{
public static Connection getConnection()
{
Connection con=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","root");
}
catch(Exception e)
{
System.out.println(e);
}
return con;
}
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 95
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("insert into
register(id, name,password,email,sex,country) values(?, ?,?,?,?,?)");
ps.setInt(1, user.getId());
ps.setString(2,user.getName());
ps.setString(3,user.getPassword());
ps.setString(4,user.getEmail());
ps.setString(5,user.getSex());
ps.setString(6,user.getCountry());
status=ps.executeUpdate();
}
catch(Exception e)
{
System.out.println(e);
}
return status;
}
public static int update(User user)
{
int status=0;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("update register set
name=?,password=?,email=?,sex=?,country=? where id=?");
ps.setString(1,user.getName());
ps.setString(2,user.getPassword());
ps.setString(3,user.getEmail());
ps.setString(4,user.getSex());
ps.setString(5,user.getCountry());
ps.setInt(6,user.getId());
status=ps.executeUpdate();
}
catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(User user)
{
int status=0;
try{
Connection con=getConnection();
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 96
PreparedStatement ps=con.prepareStatement("delete from register
where id=?");
ps.setInt(1,user.getId());
status=ps.executeUpdate();
}catch(Exception e){System.out.println(e);}
return status;
}
public static List<User> getAllRecords()
{
List<User> list=new ArrayList<User>();
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from
register");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User user=new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setSex(rs.getString("sex"));
user.setCountry(rs.getString("country"));
list.add(user);
}
}
catch(Exception e){System.out.println(e);}
return list;
}
public static User getRecordById(int id)
{
User user=null;
try{
Connection con=getConnection();
PreparedStatement ps=con.prepareStatement("select * from register
where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
while(rs.next()){
user=new User();
user.setId(rs.getInt("id"));
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 97
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setSex(rs.getString("sex"));
user.setCountry(rs.getString("country"));
}
}catch(Exception e){System.out.println(e);}
return user;
}
}
adduser-success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<p>Record successfully saved!</p>
<jsp:include page="userForm.html"></jsp:include>
</body>
</html>
adduser-error.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<body>
<p>Sorry, an error occurred!</p>
<jsp:include page="userForm.html"></jsp:include>
</body>
</html>
viewusers.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="com.dao.UserDAO, com.bean.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<body>
<h1>Users List</h1>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 98
<%
List<User> list=UserDAO.getAllRecords();
request.setAttribute("list",list);
%>
deleteuser.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="com.dao.UserDAO"%>
<jsp:useBean id="user" class="com.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="user"/>
<%
UserDAO.delete(user);
response.sendRedirect("viewusers.jsp");
%>
editform.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="com.dao.UserDAO, com.bean.User"%>
<!DOCTYPE html>
<html>
<body>
<%
String id=request.getParameter("id");
User user=UserDAO.getRecordById(Integer.parseInt(id));
%>
<h1>Edit Form</h1>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 99
<form action="edituser.jsp" method="post">
<input type="hidden" name="id" value="<%=user.getId() %>"/>
<table>
<tr><td>Name:</td><td>
<input type="text" name="name" value="<%= user.getName()%>"/></td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" value="<%=
user.getPassword()%>"/></td></tr>
<tr><td>Email:</td><td>
<input type="email" name="email" value="<%= user.getEmail()%>"/></td></tr>
<tr><td>Sex:</td><td>
<input type="radio" name="sex" value="male"/>Male
<input type="radio" name="sex" value="female"/>Female </td></tr>
<tr><td>Country:</td><td>
<select name="country">
<option>India</option>
<option>USA</option>
<option>UK</option>
<option>Canada</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Edit User"/></td></tr>
</table>
</form>
</body>
</html>
edituser.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="com.dao.UserDAO"%>
<jsp:useBean id="user" class="com.bean.User"></jsp:useBean>
<jsp:setProperty property="*" name="user"/>
<%
int i=UserDAO.update(user);
response.sendRedirect("viewusers.jsp");
%>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 100
Banking Application using JDBC – Servlets and JSP
Login.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<div>
<img src="images/bank.jpg" alt="Image" width="900" height="350">
<h2>Login</h2>
<form action="LoginServlet" method="post">
<input type="text" name="username" placeholder="Username" required>
<br>
<input type="password" name="password" placeholder="Password" required>
<br>
<input type="submit" value="Login">
</form>
<p>Not registered yet? <a href="Register.jsp">Register</a></p>
</div>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 101
Register.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
<style>
body {
text-align: center;
}
</style>
<script>
function validate()
{
var pwd = document.register.password.value;
var cnfm = document.register.confirmPassword.value;
if(pwd != cnfm)
{
alert("Password not Match with Confirm Password");
return false;
}
}
</script>
</head>
<body>
<div>
<img src="images/bank1.jpg" alt="Image" width="900" height="350">
<h2>Register</h2>
<form name="register" action="RegisterServlet" method="post" onsubmit="return
validate()">
<input type="text" name="username" placeholder="Username" required>
<br>
<input type="password" name="password" placeholder="Password" required>
<br>
<input type="password" name="confirmPassword" placeholder="Confirm Password"
required>
<br>
<input type="submit" value="Register">
</form>
<p>Already have an account? <a href="Login.jsp">Login</a></p>
</div>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 102
Create table in Oracle Database:
RegisterServlet.java:
package com.banking;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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("/RegisterServlet")
public class RegisterServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection con = null;
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try
{
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 103
con = DBConnection.get();
String user = request.getParameter("username");
String pwd = request.getParameter("password");
DBConnection.java:
package com.banking;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection
{
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 104
static Connection con=null;
static Connection get()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "root");
return con;
}
catch(Exception e)
{
return null;
}
}
}
LoginServlet.java:
package com.banking;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 105
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection con = null;
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try
{
con = DBConnection.get();
String user = request.getParameter("username");
String pwd = request.getParameter("password");
if(rs.next())
{
if(pwd.equals(rs.getString("password")))
{
HttpSession session=request.getSession();
session.setAttribute("username", user);
RequestDispatcher rd=request.getRequestDispatcher("/User.jsp");
rd.forward(request, response);
}
else
{
out.print("<h3 style='text-align : center'>Invalid User name and Password - Try Again</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Login.jsp");
rd.include(request, response);
}
}
else
{
out.print("<h3 style='text-align : center'>Invalid Record Details - Try Again</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Login.jsp");
rd.include(request, response);
}
}
catch(Exception e)
{
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 106
out.println("<h1>Exception : " + e.getMessage() + "</h1>");
out.print("<h3>Login Failed - Try Again</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Login.jsp");
rd.include(request, response);
}
finally
{
if(con != null)
{
try {
con.close();
} catch (SQLException e) {}
}
}
}
}
User.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>Welcome User</title>
<style>
body {
text-align: center;
}
h1{ text-align : center }
nav{
width : 100%
}
ul.nav
{
list-style:none;
height:36px; line-height:36px;
background:green;
font-family:Arial, Helvetica, sans-serif;
font-size:17px;
}
ul.nav li
{
border :2px solid white;
float:left;
}
ul.nav a
{
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 107
display:block;
padding:0 25px;
color:white;
text-decoration:none;
}
ul.nav a:hover, ul.nav li.current a
{
color:green;
background:white;
}
</style>
</head>
<body>
<div>
<img src="images/bank2.jpg" alt="Image" width="1000" height="200">
<h2>Welcome <%= session.getAttribute("username") %>!</h2>
<h3>Select an option from the navigation menu:</h3>
<ul class="nav">
<li><a href="createaccount.html">Create Account</a></li>
<li><a href="withdraw.html">Withdraw Amount</a></li>
<li><a href="deposit.html">Deposit Amount</a></li>
<li><a href="getdata.html">Get Details</a></li>
<li><a href="nameupdate.html">Update Details</a></li>
<li><a href="deleterecord.html">Delete Account</a></li>
<li><a href="transferamount.html">Transfer Amount</a></li>
<li><a href="CreditCard">Credit Card</a></li>
<li><a href="Logout">Logout</a></li>
</ul>
</div>
</body>
</html>
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 108
JDBC interview Questions
2. What is JDBC?
JDBC is a Java API that is used to connect the database and execute queries to perform
data operations.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 109
6. What are the steps to connect to the database in java?
Procedure Code
1 Load the Driver Class.forName("oracle.jdbc.driver.OracleDriver");
2 Establish Connection con =
Connection DriverManager.getConnection(ConnectionString,
Uname, Password);
3 Create Statement Statement st = con.createStatement();
4 Execute Query String query = “select *from student” ;
st.executeQueury(query);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 110
11. Prepared Statements are faster. Why?
• Prepared statement execution is faster than direct execution because the
statement is compiled only once.
• Prepared statements & JDBC driver are connected with each other during
execution, and there are no connection overheads.
A
12. What is ResultSet?
M
The ResultSet interface represents the database result set, which is obtained after the
execution of SQL query using Statement objects. E
E
13. What is ResultSetMetaData?
R
The ResultSetMetaData interface returns the information of table such as the total
number of columns, column name, column type, etc. P
E
14. What is DatabaseMetaData?
T
The DatabaseMetaData interface returns the information of the database such as
username, driver name, driver version, number of tables, number of views, etc.
T
15. How to call Stored Procedures in JDBC?
E
• We can execute the SQL Stored procedures through the CallableStatement
interface. C
• The CallableStatement object can be created using the prepareCall() method of H
the Connection interface.
N
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 111
18. JDBC v/s Hibernate
JDBC Hibernate
JDBC is a technology Hibernate is a framework
JDBC is sql based. We must learn sql Hibernate is object based. Only OOPs
commands. knowledge required.
JDBC is database dependent, hence query Hibernate is data base independent,
is always database specific hence code will work for all databases like
ORACLE, MySQL, SQLserver…
JDBC doesn’t have ORM tool Hibernate have ORM(Object Relational
Mapping) tool.
JDBC doesn’t provide query statistics Hibernate maintains query cache for
statistics
What is a Servlet?
• A servlet is a Java program that runs within a Web server.
• Servlets receive and respond to requests from Web clients, usually across HTTP, the
HyperText Transfer Protocol.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 112
Difference between doGet() and doPost() methods?
• The doGet() method is used to handle HTTP GET requests, which are used to retrieve
data from the server.
• The doPost() method, on the other hand, is used to handle HTTP POST requests, which
are used to submit data to the server.
Define SendRedirect?
• It is used to redirect the client to a different resource with in the web application or
between different applications, such as a servlet, JSP page, or HTML page.
Define cookies?
• Cookies in servlets are small pieces of data that are stored on the client-side by the web
browser.
• They are used to maintain user session information, track user preferences, and
personalize the user experience.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 113
JSP Interview Questions
What is JSP?
• It is a Server-Side Programming Language used to create dynamic web-pages in the
form of HTML.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 114
How do you iterate over a collection in JSP?
You can iterate over a collection in JSP using the <c:forEach> tag from the JSTL library.
What is the use of the JSP directive <%@ page import %>?
The <%@ page import %> directive is used to import Java classes or packages into the
JSP page.
How can you include external CSS or JavaScript files in a JSP page?
External CSS or JavaScript files can be included in a JSP page using the <link> or
<script> tags, respectively, within the HTML content.
What is the purpose of the JSP directive <%@ page session="false" %>?
The <%@ page session="false" %> directive is used to disable session tracking for a
particular JSP page.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 115
Define Scriptlet, Declaration and Expression tags?
1. Scriptlet: A scriptlet in JSP is a block of code that is written in Java and enclosed in the
<% and %> tags.
2. Declaration tag: A declaration tag in JSP is used to declare variables, methods, or
classes in JSP.
3. Expression tag: An expression tag in JSP is a tag that is used to evaluate an expression
and print its value to the HTML output
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 116
ORACLE
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 117
Introduction to Oracle Database
Oracle Database: An application software (relational database management system) developed
by Oracle Corporation, widely used for enterprise-level applications.
SQL (Structured Query Language): SQL is a standard language for interacting with relational
databases, including Oracle. It is used for data manipulation, retrieval, and management.
Data Storage: Oracle Database stores data in tables, rows, and columns, organized into
schemas, and accessed through SQL queries.
Data Types: Oracle supports various data types, including numeric, character, date, timestamp,
and LOB (Large Objects) for handling different types of data.
DDL (Data Definition Language): DDL is used to define and manage the database structure,
including creating, altering, and dropping database objects like tables, views, and indexes.
DML (Data Manipulation Language): DML is used to insert, update, delete, and retrieve data
from the database tables.
Functions and Aggregations: Oracle provides various built-in functions for data manipulation,
mathematical operations, and aggregate functions like SUM, AVG, MAX, MIN, and COUNT.
Clauses: Clauses are used to define specific conditions, rules, or actions that control the
behavior of the statements or blocks.
Data Integrity Constraints: Oracle enforces data integrity through constraints like NOT NULL,
UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK constraints to maintain data accuracy and
consistency.
Joins: SQL joins are used to combine data from multiple tables based on related columns,
allowing retrieval of data across different entities.
Sub Queries: Subqueries allow you to use the result of one query as a condition or value in
another query. Subqueries are a powerful feature of SQL and can be used in various clauses like
SELECT, FROM, WHERE, and HAVING.
Transactions: Oracle supports transactions to ensure data consistency and maintain the ACID
properties (Atomicity, Consistency, Isolation, Durability) of database operations.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 118
Stored Procedures: PL/SQL allows developers to create reusable code blocks in the form of
stored procedures, which can be executed and shared by multiple applications.
Views: Views in Oracle are virtual tables that present a subset of data from one or more tables,
offering security and simplifying complex queries.
Indexes: Indexes improve query performance by providing faster access to data, especially for
frequently queried columns.
Cursors: Cursors in PL/SQL are used to handle result sets returned from database queries and
enable sequential processing of data.
Triggers: Triggers are PL/SQL procedures that automatically execute in response to specific
events like insert, update, or delete operations on a table.
Exception Handling: PL/SQL provides robust exception handling mechanisms to handle errors
and unexpected situations gracefully.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 119
DDL Commands
CREATE TABLE: Creates a new table with specified columns and their data types.
ALTER TABLE: Modifies an existing table, such as adding or dropping columns or constraints.
DROP TABLE: Deletes an existing table and its data permanently.
TRUNCATE: TRUNCATE command used to remove all data from a table,
Renaming a Column:
ALTER TABLE account RENAME COLUMN name TO account_holder_name;
Dropping a Column:
ALTER TABLE account DROP COLUMN account_type;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 120
Create Tables and Inserting Records
Insert records:
1. INSERT INTO account (num, name, balance, type) VALUES (1, 'John Doe', 5000.50, 'Savings');
2. INSERT INTO account (num, name, balance, type) VALUES (2, 'Jane Smith', 3500.25, 'Checking');
3. INSERT INTO account (num, name, balance, type) VALUES (3, 'Robert Johnson', 10000.00,
'Investment');
4. INSERT INTO account (num, name, balance, type) VALUES (4, 'Emily Davis', 2000.75, 'Savings');
5. INSERT INTO account (num, name, balance, type) VALUES (5, 'Michael Wilson', 8000.00,
'Checking');
6. INSERT INTO account (num, name, balance, type) VALUES (6, 'Sophia Thompson', 6000.80,
'Savings');
7. INSERT INTO account (num, name, balance, type) VALUES (7, 'Daniel Martinez', 4000.60,
'Checking');
8. INSERT INTO account (num, name, balance, type) VALUES (8, 'Olivia Anderson', 7500.40,
'Investment');
9. INSERT INTO account (num, name, balance, type) VALUES (9, 'James Harris', 3000.90, 'Savings');
10. INSERT INTO account (num, name, balance, type) VALUES (10, 'Mia Johnson', 9000.20, 'Checking');
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 121
Operators
Oracle SQL provides various operators that are used for performing operations on data
within SQL statements
Arithmetic Operators:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulo)
Comparison Operators:
= (Equal to)
<> or != (Not equal to)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)
Logical Operators:
AND (Logical AND)
OR (Logical OR)
NOT (Logical NOT)
Null-Related Operators:
IS NULL (Checks if a value is null)
IS NOT NULL (Checks if a value is not null)
Set Operators:
UNION (Combines the result sets of two or more SELECT statements)
UNION ALL (Combines the result sets of two or more SELECT statements, including
duplicates)
INTERSECT (Returns the common rows between two SELECT statements)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 122
Retrieve Details from above table
a. SELECT * FROM account WHERE name = 'John Doe' AND balance = 5000;
15. Retrieve accounts with a balance less than 3000 or a type of 'Checking':
a. SELECT * FROM account WHERE balance < 3000 OR type = 'Checking';
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 123
16. Retrieve with a balance less than or equal to 6000 and a name not equal to 'John Doe':
a. SELECT * FROM account WHERE balance <= 6000 AND name <> 'John Doe';
17. Retrieve accounts with a balance greater than 4000 or a name starting with 'M':
a. SELECT * FROM account WHERE balance > 4000 OR name LIKE 'M%';
18. Retrieve accounts with a balance equal to 5000 or a type not equal to 'Checking':
a. SELECT * FROM account WHERE balance >= 6000 AND name LIKE '%son%';
22. Retrieve accounts with a type containing 'k' and a balance less than 4500:
a. SELECT * FROM account WHERE type LIKE '%k%' AND balance < 4500;
23. Retrieve accounts with a balance not equal to 8000 and a type starting with 'F':
a. SELECT * FROM account WHERE balance <> 8000 AND type LIKE 'F%';
24. Retrieve accounts with a balance less than 5000 or a name starting with 'J':
a. SELECT * FROM account WHERE balance < 5000 OR name LIKE 'J%';
25. Retrieve accounts with a name containing 'e' and a balance greater than 4000:
a. SELECT * FROM account WHERE name LIKE '%e%' AND balance > 4000;
26. Retrieve accounts with a balance not equal to 9000 and a type not equal to 'Finance':
a. SELECT * FROM account WHERE balance <> 9000 AND type <> 'Finance';
27. Retrieve accounts with a type containing 't' or a balance less than 3000:
a. SELECT * FROM account WHERE type LIKE '%t%' OR balance < 3000;
28. Retrieve with a balance greater than 3500 and a name not equal to 'Michael Wilson':
a. SELECT * FROM account WHERE balance > 3500 AND name <> 'Michael Wilson';
29. Retrieve accounts with a name containing 'a' or a type equal to 'HR':
a. SELECT * FROM account WHERE name LIKE '%a%' OR type = 'HR';
30. Retrieve accounts with a balance less than 4000 and a type starting with 'I':
a. SELECT * FROM account WHERE balance < 4000 AND type LIKE 'I%';
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 124
Create Employee table:
CREATE TABLE Employee (
EmpNum NUMBER,
EmpName VARCHAR2(50),
EmpDate DATE,
Salary NUMBER,
Location VARCHAR2(50),
Department VARCHAR2(50)
);
Inserting Records:
1. INSERT INTO Employee VALUES (1, 'John Doe', TO_DATE('2023-01-01', 'YYYY-MM-
DD'), 5000, 'New York', 'IT');
10. INSERT INTO Employee VALUES (10, 'Mia Johnson', TO_DATE('2023-10-01', 'YYYY-
MM-DD'), 5000, 'Berlin', 'IT');
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 125
Practice the following queries
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 126
Retrieve employees not in the 'Finance' department:
SELECT * FROM Employee WHERE Department NOT LIKE 'Finance';
Retrieve employees hired before '2022-01-01' or with a salary greater than 6000:
SELECT * FROM Employee WHERE EmpDate < TO_DATE('2022-01-01', 'YYYY-MM-DD') OR Salary
> 6000;
Retrieve employees with salaries that are not between 4000 and 6000:
SELECT * FROM Employee WHERE Salary NOT BETWEEN 4000 AND 6000;
Retrieve employees with a name that starts with 'J' and ends with 'n':
SELECT * FROM Employee WHERE EmpName LIKE 'J%n';
Retrieve employees whose names are the same length as their locations:
SELECT * FROM Employee WHERE LENGTH(EmpName) = LENGTH(Location);
Retrieve employees with a department name that starts with 'S' or ends with 'S':
SELECT * FROM Employee WHERE Department LIKE 'S%' OR Department LIKE '%S';
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 127
Aggregate functions
Aggregate functions are used to perform calculations on sets of values and return a single
result.
COUNT: This function returns the number of rows or non-null values in a column.
SUM: The SUM function calculates the sum of all values in a column.
AVG: The AVG function calculates the average of values in a column.
MIN: This function returns the minimum value in a column.
MAX: The MAX function returns the maximum value in a column.
Create Table: CREATE TABLE employees (id NUMBER, name VARCHAR2(50), department
VARCHAR2(50), salary NUMBER);
Insert Records:
INSERT INTO employees (id, name, department, salary) VALUES (1, 'John', 'IT', 5000);
INSERT INTO employees (id, name, department, salary) VALUES (2, 'Smith', 'HR', 6000);
INSERT INTO employees (id, name, department, salary) VALUES (3, 'Mike', 'Sales', 7000);
INSERT INTO employees (id, name, department, salary) VALUES (4, 'Emily', 'Marketing', 5500);
INSERT INTO employees (id, name, department, salary) VALUES (5, 'Lee', 'Finance', 6500);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 128
Clauses
WHERE Clause: The WHERE clause is used to filter the rows returned by a query.
GROUP BY Clause: The GROUP BY clause is used to group rows that have the same values in
specific columns. It is often used in conjunction with aggregate functions like SUM, AVG,
COUNT, etc.
HAVING Clause: The HAVING clause is used to filter the groups generated by the GROUP BY
clause. .
ORDER BY Clause: The ORDER BY clause is used to sort the result set based on one or more
columns. It allows you to specify the sorting order (ascending or descending) for each column.
Practice Section
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 129
Display only student name column from Student table:
SQL> select sname from student;
Display name and age of students whose location either ‘Hyderabad’ or ‘Pune’
SQL> select sname, age from student where location='hyderabad' or location='pune';
Display student detail with age less than 23 and greater than 26:
SQL> select * from student where age not between 23 and 26;
Display student details belongs to hyderbad whose age not between 23 and 26
SQL> select * from student where age not between 23 and 26 and location='hyderabad';
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 130
Display count of locations in student table:
SQL> select count(distinct location) from student;
Display student names in ascending oder with age less than 25:
SQL> select sname, age from student where age<=25 order by sname;
Display student details in descending order those who are not belongs to C and Java:
SQL> select * from student where course not in('c', 'java') order by sname desc;
Display minimum age of all students not belongs to hyberabad and pune:
SQL> select min(age) from student where location not in('hyderabad', 'pune');
Display location and students count from students of each location in descending order:
SQL> select location, count(location) from student group by location order by location desc;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 131
SQL> select min(age) from student;
SQL Constraints
SQL constraints:
• SQL constraints are used to specify rules for the data in a table.
• Constraints can be column level or table level.
Constraints are:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 132
DEFAULT: Sets a default value for a column if no value is specified
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Hyderabad'
);
Practice Section
Create table:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 133
Try inserting a duplicate name
INSERT INTO persons (name, age, email) VALUES ('John', 28, '[email protected]');
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 134
Primary Key:
• A Primary key is a unique column we set in a table.
• Using Primary key, we can easily identify records.
• A table can have only one primary key.
• The primary key column has a unique value and doesn’t store repeating values.
• A Primary key can never take NULL values.
• For example, in the case of a student when identification needs to be done in the class,
the roll number of the student plays the role of Primary key.
Syntax:
SQL> create table Persons(
2 personid int NOT NULL Primary Key,
3 lastname varchar(20) NOT NULL,
4 firstname varchar(20),
5 age int);
A Foreign key:
• A foreign key is a field or collection of fields in a table that refers to the Primary key of
the other table.
• It is responsible for managing the relationship between the tables.
• The table which contains the foreign key is often called the child table, and the table
whose primary key is being referred by the foreign key is called the Parent Table.
Syntax:
SQL> create table Orders(
2 orderid int NOT NULL,
3 ordernumber int NOT NULL,
4 PersonID int,
5 primary key (orderid),
6 foreign key(personid) references Persons(personid));
Insert Records:
SQL> insert into Orders values(1, 7789, 3);
SQL> insert into Orders values(2, 9143, 3);
SQL> insert into Orders values(3, 2277, 2);
SQL> insert into Orders values(4, 4599, 1);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 135
Sr.No Primary Key Foreign Key
1 Used to maintain the unique Used to maintain the relationship between
identification of data in the table. two or more relational tables.
2 Helps us to identify data in a Helps to identify the data in another table
database table. using the connection with the foreign key.
3 A table can have only one Primary A table can have any number of Foreign
Key. Keys.
4 The primary key is unique and Not A foreign key can contain duplicate values
Null. also.
5 Primary key can’t take Null as a A foreign key can take NULL entries also.
value.
6 Primary Key can’t be modified once A foreign key can be modified at any
entered. instance of time.
Practice Section
Create the following table with Primary Key and Foreign Key relations:
Create Company table with columns CompanyId and CompanyName with primary key column
companyId:
SQL> CREATE TABLE COMPANY(CompanyId int NOT NULL PRIMARY KEY, CompanyName varchar(20));
Insert Records:
SQL> insert into company values(1, 'DELL');
SQL> insert into company values(2, 'HP');
SQL> insert into company values(3, 'IBM');
SQL> insert into company values(4, 'MICROSOFT');
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 136
SQL> create table candidate(candidat int not null primary key, fullname varchar(20), companyid int,
foreign key(companyid) references company(companyid));
Insert Records:
SQL> insert into candidate values(1, 'Ron', 1);
SQL> insert into candidate values(2, 'Pete', 2);
SQL> insert into candidate values(3, 'Steve', 3);
SQL> insert into candidate values(4, 'Steve', NULL);
SQL> insert into candidate values(5, 'Ravi', 1);
SQL> insert into candidate values(6, 'Raj', 3);
SQL> insert into candidate values(7, 'Kiran', NULL);
Create the Following Table with Primary key and Foreign Key relation:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 137
Sub Query:
• A Query inside another Query is called Sub query.
• Sub Query can be nested inside SELECT, INSERT, UPDATE or DELETE STATEMENT.
• Sub queries can have operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Syntax:
select columns from table where columns operator(select column from table where..)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 138
SQL> create table student(sid int, sname varchar(20), age int, course varchar(20), fees int,
location varchar(20));
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 139
SQL> select max(age) from student;
Display student details of maximum age in each course from highest age to lowest:
SQL> select sname, age from student where age in (select max(age) from student group by course) order
by age desc;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 140
CREATE TABLE EMP
(EMPNO NUMBER(4) NOT NULL,
ENAME VARCHAR2(10),
JOB VARCHAR2(9),
MGR NUMBER(4),
HIREDATE DATE,
SAL NUMBER(7, 2),
COMM NUMBER(7, 2),
DEPTNO NUMBER(2));
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 141
INSERT INTO EMP VALUES
(7934, 'MILLER', 'CLERK', 7782,
TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10);
Insert Records:
INSERT INTO DEPT VALUES (10, 'ACCOUNTING', 'NEW YORK');
INSERT INTO DEPT VALUES (20, 'RESEARCH', 'DALLAS');
INSERT INTO DEPT VALUES (30, 'SALES', 'CHICAGO');
INSERT INTO DEPT VALUES (40, 'OPERATIONS', 'BOSTON');
Single Row Sub Query: In this case, the sub query always returns single row as result
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 142
Display the employees belongs to SALES department in table:
• Suppose if we know the sales dept number is 30
• We can directly run query in employee table with dept number 30
• Imaging if we don’t the dept number of SALES department (or) they have changed the
dept number of SALES then,
• We must first get the sales dept number with sub query and then pass the result as input
to outer query as follows:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 143
Display emps with salary from Max to Min:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 144
Multi Row Sub Query:
• Sub Query returns multiple rows as Result.
• We cannot give multiple rows as input to outer loop using = operator.
• We must use operators like IN as follows.
Order By Clause with Sub Query: We cannot use Order By Clause inside the Sub Query.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 145
Reason: Inner query is not meant for Final result to display. It doesn’t make sense if we order
the inner result. We have to order the final result. Hence we must place order by Clause in Outer
query.
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 146
• SCOTT salary is Higher that is 3000
• SCOTT manager id 7566 that it JONES whose salary is 2975
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 147
SQL - Joins
Joins:
• In Oracle, joins are used to combine rows from two or more tables based on a related
column between them.
• Join operations allow you to retrieve data from multiple tables by specifying the
relationship between them.
Create the Following Table with Primary key and Foreign Key relation:
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 148
Normal Join: Display the Customers along with their orders
Left Join: Display all Customers with their orders (display NULL if no order)
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 149
SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
LEFT JOIN Orders
ON Customers.customer_id = Orders.customer;
SQL Right Join: Display all records from right table with NULL if no matching in Left table
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 150
Full Outer Join: Display all matching and non matching records from tables with NULL values
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 151
Create Company table with columns CompanyId and CompanyName with primary key
column companyId:
SQL> CREATE TABLE COMPANY(CompanyId int NOT NULL PRIMARY KEY, CompanyName
varchar(20));
Insert Records:
SQL> insert into company values(1, 'DELL');
SQL> insert into company values(2, 'HP');
SQL> insert into company values(3, 'IBM');
SQL> insert into company values(4, 'MICROSOFT');
Insert Records:
SQL> insert into candidate values(1, 'Ron', 1);
SQL> insert into candidate values(2, 'Pete', 2);
SQL> insert into candidate values(3, 'Steve', 3);
SQL> insert into candidate values(4, 'Steve', NULL);
SQL> insert into candidate values(5, 'Ravi', 1);
SQL> insert into candidate values(6, 'Raj', 3);
SQL> insert into candidate values(7, 'Kiran', NULL);
Display all candidates with name and company name only if they are in company:
SQL> select fullname, companyname from candidate c1 join company c2 on c1.companyid =
c2.companyid;
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 152
Display employees belongs to IBM Company:
SQL > select fullname, companyname from candidate c1 join company c2 on c1.companyid =
c2.companyid where CompanyName like 'IBM'
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 153
Stored Procedures
Stored Procedure:
• A stored procedure is a named and precompiled collection of SQL statements and
procedural logic that resides in the database.
• It allows you to group multiple SQL commands into a single, reusable unit, which can be
called and executed from applications or other SQL statements.
Now, let's create the stored procedure to insert data into this table:
COMMIT;
END;
/
BEGIN
InsertIntoAccount(1, 'John Doe', 1000);
InsertIntoAccount(2, 'Jane Smith', 2500);
END;
/
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 154
Table Name: account
Column Data Type
num NUMBER
name VARCHAR2(50)
balance NUMBER
COMMIT;
END;
/
To execute this stored procedure and simulate a deposit operation, you can call it using PL/SQL:
BEGIN
-- Deposit 500 units into account number 1
DepositAmount(1, 500);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 155
Withdraw operation:
To execute this stored procedure and simulate a withdrawal operation, you can call it
using PL/SQL:
BEGIN
-- Withdraw 200 units from account number 1
WithdrawAmount(1, 200);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 156
Money Transfer from account to account:
-- Check if there are sufficient funds in the from account for the transfer
IF v_from_balance >= p_amount THEN
-- Perform the transfer by updating the balances for the from and to accounts
UPDATE account SET balance = v_from_balance - p_amount WHERE num =
p_from_account;
UPDATE account SET balance = v_to_balance + p_amount WHERE num = p_to_account;
COMMIT;
END IF;
END;
/
To execute this stored procedure and perform a money transfer, you can call it using PL/SQL:
BEGIN
MoneyTransfer(1, 2, 200);
MoneyTransfer(2, 1, 800);
END;
/
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 157
Oracle - Interview Questions
Write an SQL query to fetch the EmpId and FullName of all the employees
working under Manager with id is 3847
SELECT EmpId, FullName FROM EmployeeDetails WHERE ManagerId = 3847;
Write an SQL query to fetch the count of employees working in project ‘P1’.
SELECT COUNT(*) FROM EmployeeSalary WHERE Project = 'P1';
Write an SQL query to find the maximum, minimum, and average salary of the
employees
SELECT Max(Salary), Min(Salary), AVG(Salary) FROM EmployeeSalary;
Write an SQL query to find the employee id whose salary lies in the range of
9000 and 15000.
SELECT EmpId, Salary FROM EmployeeSalary WHERE Salary BETWEEN 9000 AND
15000;
Write an SQL query to fetch those employees who live in Bangalore and work
under manager with ManagerId = 1234
SELECT EmpId, City, ManagerId FROM EmployeeDetails WHERE City='Bangalore'
AND ManagerId='1234';
Write an SQL query to fetch all those employees who work on Project other
than P1.
SELECT EmpId FROM EmployeeSalary WHERE NOT Project='P1';
Write an SQL query to fetch the EmpIds that are present in both the tables –
‘EmployeeDetails’ and ‘EmployeeSalary.
SELECT EmpId FROM
EmployeeDetails
where EmpId IN
(SELECT EmpId FROM EmployeeSalary);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 158
Write an SQL query to update the employee names by removing leading and
trailing spaces.
UPDATE EmployeeDetails SET FullName = LTRIM(RTRIM(FullName));
Write an SQL query to fetch all the Employees details from EmployeeDetails
table who joined in the Year 2020.
SELECT * FROM EmployeeDetails
WHERE DateOfJoining BETWEEN '2020/01/01'
AND '2020/12/31';
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 159
What is Query to display first 5 Records from Employee table?
Select * from Employee where Rownum <= 5;
Select all records from Employee table whose name is ‘Amit’ and ‘Pradnya’
Select * from Employee where Name in(‘Amit’,’Pradnya’);
Select all records from Employee table where name not in ‘Amit’ and ‘Pradnya’
select * from Employee where name Not in (‘Amit’,’Pradnya’);
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 160
How will you differentiate between VARCHAR & VARCHAR2?
VARCHAR can store characters up to 2000 bytes while VARCHAR2 can store up to
4000 bytes
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 161