You are on page 1of 162

Advanced Java

(Oracle, JDBC, Servlets, JSP & MVC)

SRINIVAS GARAPATI

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet,


Hyderbad-500016. Contact – 9119556789 / 7306021113
Contents

S No Topic Page Num


01 Introduction to JDBC 03
02 Loading Driver 04
03 Connection to Database 05
04 Connection and Statement Interface 08
05 Static Queries Execution using Statement 09
06 ResultSet interface 11
07 PreparedStatement interface 14
08 Batch Processing 17
09 CRUD Operations using JDBC 21
10 CallableStatement interface 25
11 Transaction Management 30
12 Introduction to Servlets 35
13 Servlet Life Cycle & Web.xml file 36
14 Read Input from HTML form and display 38
15 Config and Context Parameters 39
16 DB operations from servlets 41
17 Form Validation before submit details to Server 49
18 Update Account Name by getting the details 52
19 Servlet RequestDispatcher 57
20 Session Management 60
21 Banking Project 63
22 Introduction to JSP 72
23 Database Operations from JSP 73
24 Request Dispatcher 78
25 Session Management 83
26 Login application with JSP – MVC Approach 85
27 JSTL 90
CRUD using JSTL 91
Banking Project using JDBC, Servlets & JSP 101
28 JDBC – Servlets – JSP Interview questions 109
29 Introduction to Oracle 118
30 DDL Commands 120
31 SQL Operators 122
32 SQL Aggregate functions 128
33 SQL Clauses 129
34 SQL Costraints 132
35 SQL Sub Queries 138
36 SQL Joins 148
37 SQL Stored Procedures 154
38 Oracle Interview Questions 158

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.

The following diagram explains the JDBC role in web application.

What is JDBC Driver?


• JDBC Driver is a java class that enables Java application to interact with the database

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.

Input values are:


String url = "jdbc:oracle:thin:@localhost:1521:xe";
String uname = “system”;
String pwd = “admin”;

Invoke getConnection() as follows:


Connection con = DriverManager.getConection(url, uname, pwd);

Go through briefly if you want:


• Connection URL: The connection URL for the oracle database is like
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin
is the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all
these information from the tnsnames.ora file.

• Username: The default username for the oracle database is system.

• 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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";
conn = DriverManager.getConnection(url, uname, pwd);
System.out.println("Connection is ready");
}
catch(ClassNotFoundException e1)
{
System.out.println("Exception : Driver is not present");
}
finally
{
if(conn != null)
{
conn.close();
System.out.println("Connection closed");
}
}
}
}

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

Connection interface: A Connection is a session between a Java application and a database.


Methods are:
Statement createStatement() To get the statement object to execute static queries
void setAutoCommit(boolean status) is used to set the commit status. By default, it is true.
void commit() saves the changes permanent.
void rollback() Drops all changes made.
void close() closes the connection and Releases resource.

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.

Create Statement object:


• getStatement() method of Connection returns Statement object.
• Statement interface has functionality to execute different kinds of SQL statements.
o Statement stmt = con.createStatement();

Note the followings:


• Statement interface methods are used to execute Static queries.
• Static query : A query without dynamic values – fixed query

execute() : method is used to execute DDL statements


• create table ….
• drop table …..

executeUpdate() : method is used to execute DML statements


• delete from table;

executeQuery() : method is used to execute DRL statements


• select * from table;

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 8
Executing Static Queries using Statement interface

Create table: (static query)


• execute() method of Statement object is used to execute DDL commands in database
from java application.
• It returns boolean value after executing the query

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

conn = DriverManager.getConnection(url, uname, pwd);


System.out.println("Connection is ready");

Statement stmt = conn.createStatement();


String query = "create table account(num number(5), name varchar2(30), balance
number(7))";
stmt.execute(query);
System.out.println("Table created successfully");
}
finally
{
if(conn != null){
conn.close();
System.out.println("Connection closed");
}
}
}
}

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

conn = DriverManager.getConnection(url, uname, pwd);


System.out.println("Connection is ready");

Statement stmt = conn.createStatement();


String query = "delete from account";
int count = stmt.executeUpdate(query);
System.out.println(count + " records deleted");
}
finally
{
if(conn != null){
conn.close();
System.out.println("Connection closed");
}
}
}
}

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.

Method Name Description


public boolean next(): It is used to move the cursor to the one row next from
the current position.
public int getInt(int columnIndex): It is used to return the data of specified column index
of the current row as int.
public int getInt(String It is used to return the data of specified column name
columnName): of the current row as int.
public String getString(int It is used to return the data of specified column index
columnIndex): of the current row as String.
public String getString(String It is used to return the data of specified column name
columnName): of the current row as String.

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";
conn = DriverManager.getConnection(url, uname, pwd);
System.out.println("Connection is ready");

Statement stmt = conn.createStatement();


String query = "select * from account";
ResultSet rs = stmt.executeQuery(query);

System.out.println("Account table details are : ");


while(rs.next())
{
int id = rs.getInt(1);
String name = rs.getString(2);
int balance = rs.getInt(3);
System.out.println(id + " , " + name + " , " + balance);
}
}
finally
{
if(conn != null)
{
conn.close();
System.out.println("Connection closed");
}
}
}
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 12
ResultSetMetaData

Java ResultSetMetaData Interface:


• The metadata means data about data.
• If you have to get metadata of a table like total number of column, column name,
column type etc.
• ResultSetMetaData is used to display the information of table along with table details so
that the output is more readable and understandable.
• Methods of ResultSetMetaData interface as follows:

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.

Program to display table information using ResultSetMetaData:

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("select *from account");
ResultSetMetaData rsmd = rs.getMetaData();

int count = rsmd.getColumnCount();


System.out.println("Number of Columns : " + count);

for(int i=1 ; i<=count ; i++)


{
String name = rsmd.getColumnName(i);
String type = rsmd.getColumnTypeName(i);
System.out.println("Column Name : " + name + "\tType : " + type);
}

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.

Statement st; PreparedStatement ps;


st=conn.createStatement(); String s="Update Employees SET age=? WHERE id=?";
ps=conn.prepareStatement(s);

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

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement.

Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException

Other methods of PreparedStatement:


1. public int executeUpdate() : executes the query. It is used for create, drop, insert, update,
delete etc.
2. public ResultSet executeQuery() : executes the select query. It returns an instance of
ResultSet.

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


conn = DriverManager.getConnection(url, "system", "admin");
System.out.println("Connection is ready");

String query = "insert into account values(?, ?, ?)";


PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1, 104);
ps.setString(2, "Sathya");
ps.setInt(3, 6500);
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 | 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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


conn = DriverManager.getConnection(url, "system", "admin");
System.out.println("Connection is ready");

String query = "insert into account values(?, ?, ?)";


PreparedStatement ps = conn.prepareStatement(query);
System.out.println("Enter Account details : ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
String name = scan.next();
int balance = scan.nextInt();

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();

String query = "update account set balance=balance+? where num=?";


PreparedStatement stmt=con.prepareStatement(query);
stmt.setInt(1, amt);
stmt.setInt(2, acc);
int count = stmt.executeUpdate();
System.out.println("Updated record(s) : " + count);
}
finally
{
if(con != null){
con.close();
System.out.println("Connection closed");
}
}
}
}

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.

void addBatch(String query) It adds query into batch.


int[] executeBatch() It executes the batch of queries.

Insert records into Account table from Arrays:


import java.sql.*;
public class BatchInsert{
static Connection con;
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");

int ids[] = {101, 102, 103, 104, 105};


String names[] = {"Amar", "Akbar", "Anthony", "Sheela", "Leela"};
int balances[] = {5000, 4000, 4500, 5500, 6500};

String query = "insert into account values(?,?,?)";


PreparedStatement ps = con.prepareStatement(query);

for(int i=0 ; i<=ids.length-1 ; i++)


{
ps.setInt(1, ids[i]);
ps.setString(2, names[i]);
ps.setInt(3, balances[i]);
ps.addBatch();
}
ps.executeBatch();
System.out.println("Batch executed");
}
finally{
if(con != null){
con.close();
}
}
}
}

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");

System.out.print("Enter choice : ");


int ch = scan.nextInt();

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();
}
}
}
}

static void createAccount() throws SQLException


{
System.out.println("Enter account details : ");
int num = scan.nextInt();
String name = scan.next();
int balance = scan.nextInt();
String query = "insert into account values(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
ps.setString(2, name);
ps.setInt(3, balance);
int count = ps.executeUpdate();
if(count>0)
System.out.println("Account created successfully");
else
System.out.println("Failed in creating account");
}

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");
}

static void deposit() throws SQLException


{
System.out.println("Enter account num : ");
int num = scan.nextInt();
System.out.println("Enter amount to deposit : ");
int amt = scan.nextInt();
String query = "update account set balance=balance+? where num=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, amt);
ps.setInt(2, num);

int count = ps.executeUpdate();


if(count>0)
System.out.println(amt + " deposited into acc num " + num + " successfully");
else
System.out.println("Error : Invalid account number given");
}

static void withdraw() throws SQLException


{
System.out.println("Enter account num : ");
int num = scan.nextInt();

System.out.println("Enter amount to withdraw : ");


int amt = scan.nextInt();

String query1 = "select balance from account where num=?";


PreparedStatement ps1 = con.prepareStatement(query1);
ps1.setInt(1, num);
ResultSet rs = ps1.executeQuery();

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);

String query2 = "update account set balance = balance-? where num=?";


PreparedStatement ps2 = con.prepareStatement(query2);
ps2.setInt(1, amt);
ps2.setInt(2, num);

int count = ps2.executeUpdate();


System.out.println("Account updated successfully...");
}
else
System.out.println("Error : Low balance in account");
}
else
System.out.println("Error : Invalid account number given");
}

static void moneyTransfer()


{

static void deleteAccount() throws SQLException


{
System.out.println("Enter account num to delete : ");
int num = scan.nextInt();

String query = "delete from account where num=?";


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
int count = ps.executeUpdate();
if(count>0)
System.out.println("Account deleted successfully");
else
System.out.println("Failed in deleting account");
}
}

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");

CallableStatement cstmt = conn.prepareCall("{call insert_account(?, ?, ?)}");

Scanner scanner = new Scanner(System.in);


System.out.print("Enter account number: ");
int num = scanner.nextInt();
System.out.print("Enter account name: ");
String name = scanner.next();
System.out.print("Enter account balance: ");
int balance = scanner.nextInt();

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;

IF v_balance >= p_amount THEN


p_result := 'Amount is present in the account.';
ELSE
p_result := 'Amount is not present in the account.';
END IF;
END;
/

Check the amount is present or not using Callable Statement:


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");

CallableStatement cstmt = conn.prepareCall("{call check_amount(?, ?, ?)}");

Scanner scanner = new Scanner(System.in);


System.out.print("Enter account number: ");
int accountNum = scanner.nextInt();
System.out.print("Enter amount to check: ");
int amount = scanner.nextInt();
cstmt.setInt(1, accountNum);
cstmt.setInt(2, amount);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 27
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.execute();

String result = cstmt.getString(3);


System.out.println(result);
conn.close();
}
catch (Exception e){
System.out.println("Exception : " + e.getMessage());
}
}
}

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;

-- Check if sufficient balance is present


IF v_balance >= p_amount THEN

-- Update the balance and set the result message


UPDATE account
SET balance = balance - p_amount
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");

CallableStatement cstmt = conn.prepareCall("{call withdraw_amount(?, ?, ?)}");

Scanner scanner = new Scanner(System.in);


System.out.print("Enter account number: ");
int accountNum = scanner.nextInt();
System.out.print("Enter amount to check: ");
int amount = scanner.nextInt();

cstmt.setInt(1, accountNum);
cstmt.setInt(2, amount);
cstmt.registerOutParameter(3, Types.VARCHAR);

cstmt.execute();

String result = cstmt.getString(3);


System.out.println(result);

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.

Disabling Auto-Commit Mode


• When a connection is created, it is in auto-commit mode.
• This means that each individual SQL statement is treated as a transaction and is
automatically committed right after it is executed.
• The way to allow two or more statements to be grouped into a transaction is to disable
the auto-commit mode.
o conn.setAutoCommit (false);

Commit & Rollback:


• Once you are done with your changes and you want to commit the changes then call
commit() method on connection object as follows:
o conn.commit( );
• Otherwise, to roll back updates to the database made using the Connection named
conn, use the following code:
o conn.rollback( );

Setting and Rolling Back to Save points:


• The method Connection.setSavepoint, sets a Savepoint object within the current
transaction.
• The Connection object has two new methods that help you to manage savepoints
• The following methods are used to create and delete save points.
o setSavepoint(String savepointName)
o releaseSavepoint(Savepoint savepointName)
• TheConnection.rollback method is overloaded to take a Savepoint argument.
o rollback ( String savepointName )

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.

Table before Transaction:


SQL> select *from account;
NUM NAME BALANCE
---------- -------------------- ----------
101 Amar 5000
102 Annie 7000
103 Harin 9000

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");

Scanner scan = new Scanner(System.in);

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();

System.out.println("Enter Amount to Transfer : ");


int amt = scan.nextInt();

System.out.println("Enter Acc Num to which transfer amount : ");


int dest = scan.nextInt();

con.setAutoCommit(false);

String q1 = "select balance from account where num=?";


PreparedStatement ps1 = con.prepareStatement(q1);
ps1.setInt(1, src);
ResultSet rs1 = ps1.executeQuery();
if(rs1.next())
{
int balance = rs1.getInt(1);
if(balance>=amt)
{
String q2 = "update account set balance=balance-? where num=?";
PreparedStatement ps2 = con.prepareStatement(q2);
ps2.setInt(1, amt);
ps2.setInt(2, src);
ps2.executeUpdate();
System.out.println("Amount deducted from source account");

String q3 = "update account set balance=balance+? where num=?";


PreparedStatement ps3 = con.prepareStatement(q3);
ps3.setInt(1, amt);
ps3.setInt(2, dest);
int count = ps3.executeUpdate();
if(count>0)
{
System.out.println("Amt Transferred");
con.commit();
}
else
{
System.out.println("Error : Destination account missing");
con.rollback();
System.out.println("Dont worry - Transaction will rollback");

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

Table after transaction:


SQL> select *from account;
NUM NAME BALANCE
---------- -------------------- ----------
101 Amar 8000
102 Annie 7000
103 Harin 6000

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.

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


<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.example.HelloServlet</servlet-class>
</servlet>

<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");

PrintWriter out = response.getWriter();


out.println("<h1> Hello " + name + " Welcome </h1>");
}
}

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.

Web.xml file representation:


<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>db-url</param-name>
<param-value>jdbc:mysql://localhost:3306/mydb</param-value>
</context-param>

<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;

public void init() throws ServletException


{
message = getInitParameter("message");
dbUrl = getServletContext().getInitParameter("db-url");
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
response.setContentType("text/html");
response.getWriter().println("<h1>" + message + "</h1>");
response.getWriter().println("<p>DB URL: " + dbUrl + "</p>");
}

public void destroy()


{
// Cleanup code goes here
}
}

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 40
Read Details from HTML form and Insert into Database

Create account table in database:


SQL> create table account(num number(5), name varchar2(20), balance number(9));
Table created
.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Insert Record</title>
</head>
<body>
<form action="InsertRecord" method="post">
<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>

<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);

String query = "insert into account values(?,?,?)";


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
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)
{

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 42
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}

Run the index.html file:

Enter the details then click on insert button:

Go to Database and check the record:

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

con = DriverManager.getConnection(url, uname, pwd);

String query = "select *from account where num=?";


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
pw.print("<html> <body> <h1> Account Details are : </h1>" +
"<h3> Account Number : " + rs.getInt(1) + "</h3>" +
"<h3> Name : " + rs.getString(2) + "</h3>" +
"<h3> Balance : " + rs.getInt(3) + "</h3>" +
"</body> </html>");
}
else{
pw.print("<h1> No such record to display </h1>");
}
}
catch(Exception e)
{
pw.println("<h1> Exception : " + e.getMessage() + "</h1>");
}
finally
{
if(con != null)
{
try {

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

Check the table details:

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

con = DriverManager.getConnection(url, uname, pwd);


String query = "select *from account";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if(rs != null)
{
pw.print("<h1> Details are : </h1>");

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

con = DriverManager.getConnection(url, uname, pwd);

String query = "insert into account values(?,?,?)";


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);

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

Step1 : Ask the user to input account number

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";

con = DriverManager.getConnection(url, uname, pwd);

String query = "select *from account where num=?";


PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, num);
ResultSet rs = ps.executeQuery();
if(rs.next())
{
pw.print("<html> "
+ "<body> "
+ "<form action='UpdateRecord' method='post'>"
+ "<h1> Account Details are : </h1>"
+ "<p>Number = <input type='text' name='num'
value='"
+ rs.getInt(1) + "' </p>"
+ "<p>Name = <input type='text' name='name'
value='" + rs.getString(2) + "' </p>"
+ "<p>Balance = <input type='text' name='balance'
s.getInt(3) + "' </p>"
+ "<p><input type='submit' value='update record' />
</p>"
+ "</form>"
+ "</body> "
+ "</html>");
}
else
{
pw.print("<h3> Error: Invalid Account Number </h3>" +
"<a href='index.html'> Goto Index page </a>");
}
}

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");

String url = "jdbc:oracle:thin:@localhost:1521:xe";


String uname = "system";
String pwd = "admin";
con = DriverManager.getConnection(url, uname, pwd);

String query = "update account set name = ? where num = ?";


PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, name);
ps.setInt(2, num);
ps.executeQuery();
pw.print("<h1> Record updated successfully </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 | 56
Servlet RequestDispatcher

RequestDispatcher: In Java Servlets, RequestDispatcher interface provides two methods for


including and forwarding requests from one resource (e.g., Servlet, JSP) to another resource on
the server-side:

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.

RequestDispatcher dispatcher = request.getRequestDispatcher("target.jsp");


dispatcher.forward(request, response);

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.

RequestDispatcher dispatcher = request.getRequestDispatcher("target.jsp");


dispatcher.include(request, response);

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

Redirect from Application to Application deployed in same server:


• Assume we have two applications, App1 and App2, deployed on the same server.
• We want to redirect from a Servlet in App1 to a Servlet in App2.
response.sendRedirect("http://localhost:8080/App2/MyServlet");

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();

Setting and Getting Session Attributes:


• Once you have a session object, you can set and get attributes from it.
• Session attributes are stored as key-value pairs, where both are of type Object.
// set a session attribute
session.setAttribute("username", "john");
// get a session attribute
String username = (String) session.getAttribute("username");

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

Checking if a Session Exists:


• To check if a session exists, you can call the getSession(false) method on the
HttpServletRequest object.
• If a session exists, this method returns the current session associated with this request.
• If a session does not exist, this method returns null.
HttpSession session = request.getSession(false);
if (session != null)
// session exists
else
// session does not exist

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;

if (password !== confirmPassword)


{
alert("Password and Confirm Password do not match.");
return false;
}
}
</script>
</head>
<body>
<h1>Register</h1>
<form action="RegisterServlet" method="post" onsubmit="return validateForm()">
Enter UserName : <input type="text" id="username" name="username" required><br/>
Enter Password<input type="password" id="password" name="password" required><br/>
<input type="password" id="confirmPassword" name="confirmPassword" required><br/>
<input type="submit" value="Register">
</form>
</body>
</html>

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");

Connection conn = null;

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");

Connection conn = null;

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";
}

var form = document.getElementById(formId);


form.style.display = "block";
}
</script>
</head>
<body>
<nav>
<ul>
<li><a href="#" onclick="showForm('insert_account_form');">Create
Account</a></li>
<li><a href="#" onclick="showForm('withdraw_form');">Withdraw</a></li>
<li><a href="#" onclick="showForm('deposit_form');">Deposit</a></li>
<li><a href="#">Check Balance</a></li>
<li><a href="#">Update Name</a></li>
<li><a href="#">Money Transfer</a></li>
<li><a href="./LogoutServlet">Logout</a></li>
</ul>
</nav>

<form id="insert_account_form" action="AccountCreationServlet" method="post" style="display:


none;">
<h2>Create Account</h2>
Enter Account Num : <input type="text" id="accountNumber" name="accountNumber"
required>
Enter Name : <input type="text" id="name" name="name" required>
Enter Balance : <input type="number" id="balance" name="balance" required>
<input type="submit" value="Create Account">
</form>

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>

<form id="deposit_form" action="DepositServlet" method="post" style="display: none;">


<h2>Deposit</h2>
Enter Account Num : <input type="text" id="accountNumberDeposit"
name="accountNumberDeposit" required>
Enter Deposit Amt : <input type="number" id="amountDeposit" name="amountDeposit"
required>
<input type="submit" value="Deposit">
</form>
</body>
</html>

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";

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException
{
PrintWriter out = response.getWriter();
int num = Integer.parseInt(request.getParameter("accountNumber"));
String name = request.getParameter("name");
int balance = Integer.parseInt(request.getParameter("balance"));
Connection conn = null;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, "system", "admin");

String sql = "INSERT INTO account VALUES (?, ?, ?)";


PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, num);

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
{

private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession(false);

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, expression, and declaration tags


In JSP (JavaServer Pages), scriptlet, expression, and declaration tags are used to embed Java
code into the HTML content of a web page.

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.

<p>Welcome <%= name %>!</p>

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;
}
%>

• In this example, a multiply method is declared in the declaration tag.


• It can be used in scriptlet or expression tags anywhere in the JSP page, like this:

<%
int x = 3;
int y = 4;
int result = multiply(x, y);
%>
<p>The result of <%= x %> times <%= y %> is <%= result %>.</p>

Inserting Employee details into Database Table

Create Table in Oracle Database:


create table employee(id int, name varchar2(20), salary int);

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");

String driver = "oracle.jdbc.driver.OracleDriver";


String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String password = "admin";

try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);

String sql = "INSERT INTO employee VALUES (?, ?, ?)";


PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, id);
statement.setString(2, name);
statement.setString(3, salary);

int rowsInserted = statement.executeUpdate();

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");

String sql = "SELECT name, salary FROM employee WHERE id = ?";


PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, num);
ResultSet rs = pstmt.executeQuery();

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>

Display all records from Employee Table


Consider the records present in Employee table:

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");

if (username.equals("admin") && password.equals("password"))


{
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");

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");

if (username.equals("admin") && password.equals("password"))


{
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
}
else
{
request.setAttribute("error", "Invalid username or password.");
request.getRequestDispatcher("login.jsp").include(request, response);
}
%>

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

Forward v/s SendRedirect:


• Forward is an internal redirection, while sendRedirect is an external redirection.
• In forward, the original request object is used, while in sendRedirect, a new request
object is created.
• Forward is faster and more efficient than sendRedirect, because it doesn't involve a
round-trip to the client browser.

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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.sendRedirect("redirect.jsp");
}
}

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

MVC (Model-View-Controller) is a software design pattern used in developing web


applications.

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.

Directory structure of Application:

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);

AccountDAO dao = new AccountDAO();


boolean present = dao.getData(acc);
if(present)
{
request.setAttribute("account", acc);
RequestDispatcher dispatcher =
request.getRequestDispatcher("view.jsp");
dispatcher.forward(request, response);
}
else
{
RequestDispatcher dispatcher =
request.getRequestDispatcher("error.jsp");
dispatcher.forward(request, response);
}
}
}

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:out> - This tag is used to display the value of a variable.


<c:out value="${user.name}" />

<c:set> - This tag is used to set a variable with a value.


<c:set var="count" value="10" />

<c:remove> - This tag is used to remove a variable.


<c:remove var="count" />

<c:if> - This tag is used for conditional execution of code.


<c:if test="${user.isAdmin}">
<!-- Display admin-specific content -->
</c:if>

<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:import> - This tag is used to include content from an external resource.


<c:import url="external.jsp" />

<c:url> - This tag is used for encoding URLs to ensure proper formatting.
<a href="<c:url value='/products?id=1' />">Product 1</a>

<c:redirect> - This tag is used to perform a server-side redirect.


<c:redirect url="newpage.jsp" />

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>

Create register table in Oracle DB:

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;
}

public static int save(User user)


{

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);
%>

<table border="1" width="90%">


<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
<c:forEach items="${list}" var="u">
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</td>
<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
</c:forEach>
</table>
<br/><a href="adduserform.jsp">Add New User</a>
</body>
</html>

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");

String query = "insert into register values(?, ?)";


PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pwd);
int count = ps.executeUpdate();
if(count>0)
{
out.print("<h3 style='text-align:center'>Successfully Registered - Login Now</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Login.jsp");
rd.include(request, response);
}
else
{
out.print("<h3 style='text-align:center'>Registration Failed - Try Again</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Register.jsp");
rd.include(request, response);
}
}
catch(Exception e)
{
out.println("<h3 style='text-align:center'>Exception : " + e.getMessage() + "</h3>");
out.print("<h3 style='text-align:center'>Registration Failed - Try Again</h3>");
RequestDispatcher rd=request.getRequestDispatcher("/Register.jsp");
rd.include(request, response);
}
finally
{
if(con != null)
{
try {
con.close();
} catch (SQLException e) {}
}
}
}
}

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");

String query = "select password from register where uname=?";


PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, user);
ResultSet rs = ps.executeQuery();

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>

Create Account table to perform all account operations:


CREATE TABLE account (
num INT NOT NULL UNIQUE,
name VARCHAR2(20) NOT NULL,
balance INT NOT NULL
);

Note: Complete the project by yourself or watch video in AmeerpetTechnologies channel

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 108
JDBC interview Questions

1. Explain SQL Commands:


DDL DML DRL DCL
Data Definition Language Data Manipulation Data Retrieval Data Control
commands Language commands Language language
commands commands
CREATE to create a new INSERT to insert a Select: Used to COMMIT to
table or database. new row. retrieve table permanently save.
information
ALTER for alteration. UPDATE to update an ROLLBACK to
existing row. undo the change.
TRUNCATE to delete
data from the table. DELETE to delete a SAVEPOINT to
row. save temporarily.
DROP to drop a table.
MERGE for merging
RENAME to rename a
two rows or two
table.
tables.

2. What is JDBC?
JDBC is a Java API that is used to connect the database and execute queries to perform
data operations.

3. What is JDBC Driver?


JDBC Driver is a java class that enables Java application to interact with the database

4. What are the types of JDBC Drivers


i. JDBC- ODBC Bridge driver / Sun Driver
ii. Native API Driver
iii. Network Protocol Driver
iv. Thin Driver – Oracle Driver

5. What are the JDBC statements?


There are 3 types of JDBC Statements, as given below:
i. Statement: It is used to execute static SQL queries.
ii. Prepared Statement: Used when we want to execute SQL statement repeatedly.
Input data is dynamic and taken input at the run time.
iii. Callable Statement: Used when we want to execute stored procedures.

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);

7. What is the role of Class.forName while loading drivers?


Class.forName creates an instance of JDBC driver and register with DriverManager.

8. What is DriverManager in JDBC?


DriverManager is a mediator between the Java Application and Database.
We must register the driver at DriverManager before its use.

9. Explain execute(), executeUpdate(), executeQuery() methods?


executeUpdate() executeQuery() execute()
This method is used to This method is used to This method is used to
execute DML queries execute DRL queries execute DDL queries
It returns int value to This method returns a This method returns a
represent how many rows ResultSet object contains Boolean value.
effected. Records information
DML->INSERT , UPDATE Example: SELECT Example: Create, drop,
and DELETE Truncate

10. Explain Statement, PreparedStatement and CallableStatement?


Statement PreparedStatement CallableStatement
It is used to execute It is used to execute sql It is used to access stored
static sql queries statement many times. procedures.
Doesn’t accept input Access input parameters at Access input parameters at
parameters runtime. runtime.
They are – IN, OUT and IN
OUT.
Statement st; PreparedStatement ps; CallableStatement cs;
st=conn.createState String s = "Update Employees String s = "{call getEmpName
ment(); SET age = ? WHERE id = ?"; (?, ?)}";
ps=conn.prepareStatement(s); cs = conn.prepareCall (s);

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

16. What is Transaction Management? O


The sequence of actions (SQL statements) is treated as a single unit that is known as a L
transaction.
O
17. Explain Commit, Rollback and SavePoint in JDBC G
Commit Rollback SavePoint
commit() : It is used rollback(): undo the Roll back to some of them I
to save the changes. If any of the instead of rollback everything E
transaction SQL statements are
permanently. failed. S
con.commit(); con.rollback(); Savepoint sp =
con.setSavepoint();
insertStmt.executeUpdate();
con.rollback(sp);
con.commit();

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

19. JDBC v/s JDBC template


20. Problems in JDBC:
• We need to write a lot of code before and after executing the query such as Load
Driver, Get connection, Create statement, Execute query, Close ResultSet if any
and Close connection.
• Need to handle exceptions in database logic only.
• Need to handle transaction.

21. Solution is JdbcTemplate


Spring JdbcTemplate eliminates all the above-mentioned problems of JDBC API. It
provides you methods to write the queries directly, so it saves a lot of work and time.

Interview Questions on Servlets

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.

What is the life cycle of servlet?


• Servlet is loaded
• servlet is instantiated
• servlet is initialized
• service the request
• servlet is destroyed

Who is responsible to create the object of servlet?


• The web container or servlet container. We can understand this by defining default
constructor inside the servlet class.

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.

Differentiate config and context parameters?


• Context parameters are configuration parameters that are set at the web application
level and are available to all servlets and JSP pages within that application.
• Config parameters, are servlet level and are used to pass input to Servlet via config
object.

Define Servlet RequestDispatcher?


• It is used to transfer control from one servlet or JSP page to another servlet or JSP page
during runtime.
• It is also used to include the content of HTML or JSP page.

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.

Define deployment descriptor?


• A deployment descriptor in Java Servlets is an XML file named web.xml that describes
how a web application should be deployed and configured.
• It provides a way to define application-wide configuration parameters, such as servlets,
filters and error pages.

What is session management?


• Maintaining stateful information about a user's interaction with a web application across
multiple requests and responses.

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.

What is the difference between JSP and Servlet?


Servlets are Java programs that handle requests and generate responses, while JSP is a
technology that allows embedding Java code into HTML pages for dynamic content generation.

What is the lifecycle of a JSP page?


JSP lifecycle includes six phases: translation, compilation, initialization, execution, service,
and destruction.

How do you declare a variable in JSP?


You can declare a variable in JSP using the <% ! %> declaration tag or by using scriptlets
<% %>. For example: <% int count = 0; %>.

How can you include another JSP page in a JSP?


You can include another JSP page using the <jsp:include> tag or by using <%@ include
file="filename.jsp" %> directive.

What is the purpose of the JSP expression <%= %>?


The JSP expression <%= %> is used to evaluate and display the result of an expression
within the HTML content.

What is the difference between <jsp:forward> and <jsp:include>?


<jsp:forward> forwards the request to another resource on the server, while
<jsp:include> includes the content of another resource in the current JSP page.

How do you handle exceptions in JSP?


You can handle exceptions in JSP using the <%@ page errorPage="error.jsp" %>
directive to specify an error handling page.

What are implicit objects in JSP?


Implicit objects in JSP are predefined objects that are available for use without explicitly
declaring them. Some common implicit objects are request, response, session, out, pageContext,
etc.

What is the difference between request.getParameter() and request.getAttribute()?


request.getParameter() retrieves the value of a request parameter, while
request.getAttribute() retrieves the value of a request attribute set by the servlet or another JSP
page.

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 difference between include and forward methods in JSP?


The include method includes the content of another resource in the current page and
continues processing the remaining content, while the forward method forwards the request to
another resource and stops processing the current page.

How do you handle sessions in JSP?


Sessions can be managed in JSP using the implicit session object, which allows storing
and retrieving session data using methods like setAttribute() and getAttribute().

How do you set cookies in JSP?


Cookies can be set in JSP using the response.addCookie() method, which takes a Cookie
object as a parameter.

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:useBean> tag?


The <jsp:useBean> tag is used to instantiate a JavaBean or locate an existing instance of
a JavaBean for use in a JSP page.

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.

How can I use JSP in the MVC model?


• JSP is used in MVC in the presentation tasks. It is used as a view.

What do you mean by Context Initialization Parameters?


• Context Initialization Parameters are the Initializing Parameters for the whole application.

Mention the scope values for <jsp.useBean> tag?


1. page
2. request
3. application
4. session

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

Mention the Implicit Objects in a JSP?


1. Request
2. Response
3. Application
4. Exception
5. Config
6. Page
7. Session
8. PageContext
9. Out

How can we stop errors on Display in a JSP Page?


• We can stop errors in display in a JSP Page by setting up "isErrorpage="TRUE".

What are the different Life-Cycle methods?


The different Life-Cycle Methods are as follows:
1. jspInit()
2. _jspService()
3. jspDestroy

Define Page directive?


• It is used to provide instructions to the JSP container about how to process the JSP page.
<%@ page attribute="value" %>

What are action tags in jsp?


• Action tags are special tags that are used to perform dynamic actions within a JSP page.
• Examples: Forward, Include, UseBean, SetProperty etc.

What are the main attributes on page directives?


1. Session: It is designed to show if any session data is available to the page or not.
2. Import: It is dedicated show packages that are imported.

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.

PL/SQL (Procedural Language/Structured Query Language): PL/SQL is Oracle's proprietary


extension of SQL that allows developers to write procedural code within the database, enabling
data processing in application like transactions.

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,

Creating simple account table:


CREATE TABLE account (
id INT,
name VARCHAR2(20),
balance NUMBER(10, 2)
);

Adding a New Column:


ALTER TABLE account ADD account_type VARCHAR2(20);

Modifying Column Data Type:


ALTER TABLE account MODIFY balance NUMBER(12, 2);

Renaming a Column:
ALTER TABLE account RENAME COLUMN name TO account_holder_name;

Dropping a Column:
ALTER TABLE account DROP COLUMN account_type;

Adding a Default Value to a Column:


ALTER TABLE account ALTER COLUMN balance SET DEFAULT 0;

Dropping the Table:


DROP TABLE account;

Truncating the Table (Removing all Data):


TRUNCATE TABLE account;

Renaming the Table:


ALTER TABLE account RENAME TO new_account_table;

Adding a Primary Key Constraint:


ALTER TABLE account ADD CONSTRAINT pk_account PRIMARY KEY (id);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 120
Create Tables and Inserting Records

Create following tables:


CREATE TABLE Students (
ID NUMBER, CREATE TABLE Products (
Name VARCHAR2(50), ProductID NUMBER,
Course VARCHAR2(50), ProductName VARCHAR2(100),
Fees NUMBER Price NUMBER
); );

CREATE TABLE Payments ( CREATE TABLE Orders (


PaymentID NUMBER, OrderID NUMBER,
CustomerID NUMBER, CustomerID NUMBER,
Amount NUMBER, OrderDate DATE,
PaymentDate DATE TotalAmount NUMBER
); );

Create Account table:


CREATE TABLE account (
num INT,
name VARCHAR2(100),
balance NUMBER(10, 2),
type VARCHAR2(50)
);

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)

Pattern Matching Operators:


LIKE (Matches a pattern)
NOT LIKE (Does not match a pattern)

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

1. Retrieve all records:


a. SELECT * FROM account;
2. Retrieve accounts with balance greater than 5000:
a. SELECT * FROM account WHERE balance > 5000;
3. Retrieve accounts with a balance equal to 5000:
a. SELECT * FROM account WHERE balance = 5000;
4. Retrieve accounts with a balance not equal to 4000:

a. SELECT * FROM account WHERE balance <> 4000;


5. Retrieve accounts with a balance less than or equal to 3500:
a. SELECT * FROM account WHERE balance <= 3500;
6. Retrieve accounts with the name 'John Doe':
a. SELECT * FROM account WHERE name = 'John Doe';
7. Retrieve accounts with the name starting with 'M':
a. SELECT * FROM account WHERE name LIKE 'M%';
8. Retrieve accounts with the name containing 'son':

a. SELECT * FROM account WHERE name LIKE '%son%';


9. Retrieve accounts with type 'Savings':

a. SELECT * FROM account WHERE type = 'Savings';


10. Retrieve accounts with type not equal to 'Investment':
a. SELECT * FROM account WHERE type <> 'Investment';
11. Retrieve accounts with the number equal to 7:
a. SELECT * FROM account WHERE num = 7;
12. Retrieve accounts with the number between 3 and 8:
a. SELECT * FROM account WHERE num BETWEEN 3 AND 8;
13. Retrieve accounts with the number outside the range 1 to 6:

a. SELECT * FROM account WHERE num NOT BETWEEN 1 AND 6;


14. Retrieve accounts with a name of 'John Doe' and a balance of 5000:

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 = 5000 OR type <> 'Checking';


19. Retrieve accounts with a name containing 'son' and a type equal to 'Savings':
a. SELECT * FROM account WHERE name LIKE '%son%' AND type = 'Savings';
20. Retrieve accounts with a name starting with 'D' or a type starting with 'C':
a. SELECT * FROM account WHERE name LIKE 'D%' OR type LIKE 'C%';
21. Retrieve with a balance greater than or equal to 6000 and a name containing 'son':

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');

2. INSERT INTO Employee VALUES (2, 'Jane Smith', TO_DATE('2023-02-01', 'YYYY-


MM-DD'), 5500, 'London', 'Finance');

3. INSERT INTO Employee VALUES (3, 'Robert Johnson', TO_DATE('2023-03-01',


'YYYY-MM-DD'), 6000, 'Paris', 'Marketing');

4. INSERT INTO Employee VALUES (4, 'Emily Davis', TO_DATE('2023-04-01', 'YYYY-


MM-DD'), 4500, 'Berlin', 'HR');

5. INSERT INTO Employee VALUES (5, 'Michael Wilson', TO_DATE('2023-05-01', 'YYYY-


MM-DD'), 5500, 'Tokyo', 'IT');

6. INSERT INTO Employee VALUES (6, 'Sophia Thompson', TO_DATE('2023-06-01',


'YYYY-MM-DD'), 4000, 'Sydney', 'Finance');

7. INSERT INTO Employee VALUES (7, 'Daniel Martinez', TO_DATE('2023-07-01',


'YYYY-MM-DD'), 7000, 'New York', 'Sales');

8. INSERT INTO Employee VALUES (8, 'Olivia Anderson', TO_DATE('2023-08-01',


'YYYY-MM-DD'), 6000, 'London', 'Marketing');

9. INSERT INTO Employee VALUES (9, 'James Harris', TO_DATE('2023-09-01', 'YYYY-


MM-DD'), 4500, 'Paris', 'HR');

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

Retrieve all employees:


SELECT * FROM Employee;

Retrieve employees with a salary greater than 5000:


SELECT * FROM Employee WHERE Salary > 5000;

Retrieve employees located in 'New York':


SELECT * FROM Employee WHERE Location = 'New York';

Retrieve employees hired on or after '2022-01-01':


SELECT * FROM Employee WHERE EmpDate >= TO_DATE('2022-01-01', 'YYYY-MM-DD');

Retrieve employees with a salary between 4000 and 6000:


SELECT * FROM Employee WHERE Salary BETWEEN 4000 AND 6000;

Retrieve employees in the 'IT' department:


SELECT * FROM Employee WHERE Department = 'IT';

Retrieve employees with names starting with 'J':


SELECT * FROM Employee WHERE EmpName LIKE 'J%';

Retrieve employees with names ending with 'son':


SELECT * FROM Employee WHERE EmpName LIKE '%son';

Retrieve employees with names containing 'th':


SELECT * FROM Employee WHERE EmpName LIKE '%th%';

Retrieve employees with null values for the 'Location' column:


SELECT * FROM Employee WHERE Location IS NULL;

Retrieve employees with non-null values for the 'Location' column:


SELECT * FROM Employee WHERE Location IS NOT NULL;

Retrieve employees with salaries equal to 5000 or 6000:


SELECT * FROM Employee WHERE Salary IN (5000, 6000);

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 of exactly 7 characters:


SELECT * FROM Employee WHERE LENGTH(EmpName) = 7;

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';

Retrieve employees whose names are not 'John' or 'Jane':


SELECT * FROM Employee WHERE EmpName NOT IN ('John', 'Jane');

Retrieve employees whose names are alphabetically after 'John':


SELECT * FROM Employee WHERE EmpName > 'John';

Retrieve employees with a name that contains exactly three characters:


SELECT * FROM Employee WHERE LENGTH(EmpName) = 3;

Retrieve employees with a salary that is not equal to 5000:


SELECT * FROM Employee WHERE Salary <> 5000;

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);

Retrieve the total number of employees:


SELECT COUNT(*) FROM employees;

Calculate the average salary of all employees:


SELECT AVG(salary) FROM employees;

Find the highest salary among all employees:


SELECT MAX(salary) FROM employees;

Find the lowest salary among all employees:


SELECT MIN(salary) FROM employees;

Retrieve the total salary for the IT department:


SELECT SUM(salary) FROM employees WHERE department = 'IT';

Calculate the average salary for the Sales department:


SELECT AVG(salary) FROM employees WHERE department = 'Sales';

Find the employee with the highest salary:


SELECT name, MAX(salary) FROM employees;

Find the employee with the lowest salary:


SELECT name, MIN(salary) FROM employees;

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

Create table with name Student:


SQL> create table student(sid int, sname varchar(20), age int, course varchar(20), fees int,
location varchar(20));

Insert records into Student table:


insert into student values(101, 'ram', 24, 'java', 12000, 'hyderabad');
insert into student values(102, 'amar', 27, 'c', 5000, 'pune');
insert into student values(103, 'satya', 21, 'python', 9000, 'chennai');
insert into student values(104, 'pavan', 28, 'android', 8000, 'hyderabad');
insert into student values(105, 'harin', 22, 'java', 12000, 'bangalore');
insert into student values(106, 'swathi', 19, 'android', 8000, 'chennai');
insert into student values(107, 'raji', 20, 'c', 5000, 'pune');
insert into student values(108, 'jaya', 25, 'java', 12000, 'hyderabad');
insert into student values(109, 'harsha', 29, 'python', 9000, 'chennai');
insert into student values(110, 'vijaya', 20, 'java', 12000, 'hyderabad');

Display all records from Student table:


SQL> select * from student;
sid sname age course fees location
101 ram 24 java 12000 hyderabad
102 amar 27 c 5000 pune
103 satya 21 python 9000 chennai
104 pavan 28 android 8000 hyderabad
105 harin 22 java 12000 bangalore
106 swathi 19 android 8000 chennai
107 raji 20 c 5000 pune
108 jaya 25 java 12000 hyderabad
109 harsha 29 python 9000 chennai
110 vijaya 20 java 12000 hyderabad

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 student details with name='harin'


SQL> select * from student where sname='harin';

Display students belongs to location ‘Hyderabad’


SQL> select * from student where location='hyderabad';

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 names whose age greater than 25


SQL> select sname from student where age > 25;

Display students belongs to hyderbad or pune or chennai:


SQL> select sname from student where location in ('hyderabad', 'pune', 'chennai');
(or)
SQL> select sname from student where location='hyderabad' or location='pune' or location='chennai';

Display all student details except pune location:


SQL> select * from student where location != 'pune';
Display student details from age 23 to 26:
SQL> select * from student where age>=23 and age<=26;
(or)
SQL> select * from student where age between 23 and 26;

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 whose age not between 23 and 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';

Display number of records in Student table:


SQL> select count(*) from student;
(or)
SQL> select count(sid) from student;

16. Display minimum age among all students:


SQL> select min(age) from student;

Display all locations in student table:


SQL> select distinct location from student;

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 order:


SQL> 131select sname from student order by sname asc;

Display student names by age in descending order:


SQL> select sname, age from student order by age desc;

Display student names whose age from 25 with age(ascending oder) :


SQL> select sname, age from student where age>=25 order by age;

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 students count belongs to chennai location:


SQL> select count(sname) from student where location='chennai';

Display student count belongs to both pune and bangalore locations:


SQL> select count(sname) from student where location in('pune', 'bangalore');

Display maximum age of all students belongs to hyderad location:


SQL> select max(age) from student where location='hyderabad';

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:


SQL> select location, count(location) from student group by location;

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;

Display number of students in each group from student table:


SQL> select course, count(course) from student group by course;

Display number of students in each group only if count is more than 2:


SQL> select course, count(course) from student group by course having count(course)>2;

Display maximum age of student in each location:


SQL> select location , max(age) from student group by location;

Display Min age among all students:

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

NOT NULL: Column cannot have a NULL value


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

UNIQUE: All values in a column are different


CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

CHECK: Ensures that the values in a column satisfies a specific condition


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

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

Assuming the table has the following structure:


Column Data Type Constraints
id INT PRIMARY KEY, AUTO_INCREMENT
name VARCHAR(50) NOT NULL, UNIQUE
age INT CHECK (age >= 18 AND age <= 120)
email VARCHAR(100) CHECK (email LIKE '%@%.%')
date_of_birth DATE DEFAULT '2000-01-01'

Create table:

CREATE TABLE persons (


id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL UNIQUE,
age INT CHECK (age >= 18 AND age <= 120),
email VARCHAR(100) CHECK (email LIKE '%@%.%'),
date_of_birth DATE DEFAULT '2000-01-01'
);

Insert 6 records into the table:

INSERT INTO persons (name, age, email, date_of_birth) VALUES


('John', 30, 'john@example.com', '1993-07-15'),
('Smith', 25, 'smith@example.com', '1998-02-20'),
('Michael', 42, 'michael@example.com', '1981-11-05'),
('Brown', 22, 'brown@example.com', '2000-08-10'),
('Lee', 28, 'lee@example.com', '1995-04-30'),
('Lisa', 19, 'lisa@example.com', '2004-06-12');

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, 'john@example.com');

Try inserting another duplicate name


INSERT INTO persons (name, age, email) VALUES ('Michael', 33, 'michael@example.com');

Try inserting a record without a name


INSERT INTO persons (age, email) VALUES (30, 'test@example.com');

Try inserting a record without an age


INSERT INTO persons (name, email) VALUES ('Test Person', 'test@example.com');

Try inserting a record with age less than 18


INSERT INTO persons (name, age, email) VALUES ('Young', 12, 'young@example.com');

Try inserting a record with age greater than 120


INSERT INTO persons (name, age, email) VALUES ('Old', 150, 'old@example.com');

Try inserting a record with an invalid email format


INSERT INTO persons (name, age, email) VALUES ('Invalid Email', 25, 'invalid_email');

Try inserting a record with an email without a domain


INSERT INTO persons (name, age, email) VALUES ('No Domain', 30, 'nodomain@');

Try inserting a record without providing a date_of_birth


INSERT INTO persons (name, age, email) VALUES ('No Birthdate', 40,
'nobirthdate@example.com');

Try inserting a record with a NULL date_of_birth


INSERT INTO persons (name, age, email, date_of_birth) VALUES ('Null Birthdate', 35,
'nullbirthdate@example.com', NULL);

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);

Insert Records into Persons table:


SQL> insert into Persons values(1, 'Amar', 'G', 23);
SQL> insert into Persons values(2, 'Annie', 'P', 21);
SQL> insert into Persons values(3, 'Harin', 'K', 22);

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');

Create Candidate table:

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:

Create Tables and Insert records:


-- Creating the customers table
CREATE TABLE customers (
customer_id NUMBER NOT NULL PRIMARY KEY,
first_name VARCHAR 2(50)
);

-- Creating the orders table


CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
amount NUMBER,
customer NUMBER,
FOREIGN KEY (customer) REFERENCES customers(customer_id)
);

SQL SUB Queries

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.

Rule: Every Sub Query must be placed inside the parenthesis.

Syntax:
select columns from table where columns operator(select column from table where..)

Display Customer details with minimum age:


• As we don’t know the minimum age in the table, first we need to find the minimum age
with sub query.
• Pass the result of sub query(min age) as input to parent query.
• Get the result from Parent query

SELECT * FROM Customers WHERE age = (SELECT MIN(age) FROM Customers);

Create table with name Student:

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));

Insert records into Student table:


insert into student values(101, 'ram', 24, 'java', 12000, 'hyderabad');
insert into student values(102, 'amar', 27, 'c', 5000, 'pune');
insert into student values(103, 'satya', 21, 'python', 9000, 'chennai');
insert into student values(104, 'pavan', 28, 'android', 8000, 'hyderabad');
insert into student values(105, 'harin', 22, 'java', 12000, 'bangalore');
insert into student values(106, 'swathi', 19, 'android', 8000, 'chennai');
insert into student values(107, 'raji', 20, 'c', 5000, 'pune');
insert into student values(108, 'jaya', 25, 'java', 12000, 'hyderabad');
insert into student values(109, 'harsha', 29, 'python', 9000, 'chennai');
insert into student values(110, 'vijaya', 20, 'java', 12000, 'hyderabad');

3. Display all records from Student table:


SQL> select * from student;

sid sname age course fees location


101 ram 24 java 12000 hyderabad
102 amar 27 c 5000 pune
103 satya 21 python 9000 chennai
104 pavan 28 android 8000 hyderabad
105 harin 22 java 12000 bangalore
106 swathi 19 android 8000 chennai
107 raji 20 c 5000 pune
108 jaya 25 java 12000 hyderabad
109 harsha 29 python 9000 chennai
110 vijaya 20 java 12000 hyderabad

Display Student Name, Age from Student having minimum age:


SQL> select sname, age from student where age=(select min(age) from student);

Display minimum age of hyderabad location:


SQL> select min(age) from student where location='hyderabad';

Display student details belongs to hyderabad location with minimum age:


SQL> select sname, age, location from student where age=(select min(age) from student where
location='hyderabad') and location='hyderabad';

Display maximum age in student table:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 139
SQL> select max(age) from student;

Display student details with maximum age:


SQL> select sname, age from student where age=(select max(age) from student);

Display maximum age in each course:


SQL> select course, max(age) from student group by course;

Display student details of maximum age in each course:


SQL> select sname, age from student where age in (select max(age) from student group by course);

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;

Display student names those who paid minimum fees:


SQL> select sname from student where fees = (select min(fees) from student);

Display max, min ages from student


SQL> select max(age) as max_age, min(age) as min_age from student;

Display Second Maximum age


SQL> SELECT MAX(AGE) FROM STUDENT WHERE AGE < (SELECT MAX(AGE) FROM STUDENT);

Display Second Minimum age


SQL> SELECT MIN(AGE) FROM STUDENT WHERE AGE > (SELECT MIN(AGE) FROM STUDENT);

Display Third Maximum age


SQL> SELECT MAX(AGE) AS THIRD_MAX_AGE FROM STUDENT WHERE AGE < (SELECT MAX(AGE) FROM
STUDENT WHERE AGE < (SELECT MAX(AGE) FROM STUDENT));

Display second highest course fees


SQL> SELECT MAX(FEES) AS SECOND_MAX_FEES FROM STUDENT WHERE FEES<(SELECT MAX(FEES)
FROM STUDENT)

Display student name with minimum age belongs to PUNE location


SQL> SELECT SNAME, AGE FROM STUDENT WHERE AGE=(SELECT MIN(AGE) FROM STUDENT WHERE
LOCATION LIKE 'PUNE') AND LOCATION LIKE 'PUNE';

Create Emp table:

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));

Insert following data:


INSERT INTO EMP VALUES
(7369, 'SMITH', 'CLERK', 7902,
TO_DATE('17-DEC-1980', 'DD-MON-YYYY'), 800, NULL, 20);
INSERT INTO EMP VALUES
(7499, 'ALLEN', 'SALESMAN', 7698,
TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30);
INSERT INTO EMP VALUES
(7521, 'WARD', 'SALESMAN', 7698,
TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30);
INSERT INTO EMP VALUES
(7566, 'JONES', 'MANAGER', 7839,
TO_DATE('2-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20);
INSERT INTO EMP VALUES
(7654, 'MARTIN', 'SALESMAN', 7698,
TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30);
INSERT INTO EMP VALUES
(7698, 'BLAKE', 'MANAGER', 7839,
TO_DATE('1-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30);
INSERT INTO EMP VALUES
(7782, 'CLARK', 'MANAGER', 7839,
TO_DATE('9-JUN-1981', 'DD-MON-YYYY'), 2450, NULL, 10);
INSERT INTO EMP VALUES
(7788, 'SCOTT', 'ANALYST', 7566,
TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES
(7839, 'KING', 'PRESIDENT', NULL,
TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10);
INSERT INTO EMP VALUES
(7844, 'TURNER', 'SALESMAN', 7698,
TO_DATE('8-SEP-1981', 'DD-MON-YYYY'), 1500, 0, 30);
INSERT INTO EMP VALUES
(7876, 'ADAMS', 'CLERK', 7788,
TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20);
INSERT INTO EMP VALUES
(7900, 'JAMES', 'CLERK', 7698,
TO_DATE('3-DEC-1981', 'DD-MON-YYYY'), 950, NULL, 30);
INSERT INTO EMP VALUES
(7902, 'FORD', 'ANALYST', 7566,
TO_DATE('3-DEC-1981', 'DD-MON-YYYY'), 3000, NULL, 20);

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);

Create dept table:


CREATE TABLE DEPT
(DEPTNO NUMBER(2),
DNAME VARCHAR2(14),
LOC VARCHAR2(13) );

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');

In Oracle: (To check the records in proper manner)


Sql> set linesize 100;
Sql> set pagesize 100;
Sql> select * from emp;

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:

Find the deptno of SALES department:

Display Employees belongs to SALES department:

Find the Second Highest salary in emp table:

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 143
Display emps with salary from Max to Min:

Printing max salary in emp table:

Printing Second highest salary in emp table:

Display second max salary with sub query:

Display Third Max salary with Sub Query:

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.

Display the employees belongs to departments SALES AND RESEARCH:

Display dept numbers of SALES and RESEARCH:

If we try to write sub query to display employees results Error:

We must use IN operator to display the information 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.

Co-related Sub Query:


Query: Display the employees earning more salary than their managers

From the above table:

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

We must use Self Join in Sub Query:


What is Self Join?
Self join in used to join the table itself.

Display employee names with their Managers:

Display employees with their managers along with their salaries:

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:

Create Tables and Insert records:


-- Creating the customers table
CREATE TABLE customers (
customer_id NUMBER NOT NULL PRIMARY KEY,
first_name VARCHAR 2(50)
);

-- Creating the orders table


CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
amount NUMBER,
customer NUMBER,
FOREIGN KEY (customer) REFERENCES customers(customer_id)
);

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 148
Normal Join: Display the Customers along with their orders

SELECT Customers.customer_id, Customers.first_name, Orders.amount


FROM Customers
JOIN Orders
ON Customers.customer_id = Orders.customer;

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

SELECT Customers.customer_id, Customers.first_name, Orders.amount


FROM Customers
RIGHT JOIN Orders
ON Customers.customer_id = Orders.customer;

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

SELECT Customers.customer_id, Customers.first_name, Orders.amount


FROM Customers
FULL OUTER JOIN Orders
ON Customers.customer_id = Orders.customer;

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');

Create Candidate table:


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);

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;

Display all candidate with name and company name:


SQL> select fullname, companyname from candidate c1 left 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'

Display employees not belongs to IBM company:


SQL > select fullname, companyname from candidate c1 join company c2 on c1.companyid =
c2.companyid where CompanyName not like 'IBM'

Display employees working in both IBM and HP company:


SQL > select fullname, companyname from candidate c1 join company c2 on c1.companyid =
c2.companyid where CompanyName IN ('IBM', 'HP')

Display count of employees belongs to IBM company:


SQL > select COUNT(candidat) AS IbmEmpCnt from candidate c1 join company c2 on
c1.companyid = c2.companyid where CompanyName IN ('IBM')

Display how many employees belongs to Microsoft company:


SQL > select fullname, companyname from candidate c1 join company c2 on c1.companyid =
c2.companyid where CompanyName LIKE 'MICROSOFT'

Display candidates without job:


SQL > select fullname, companyname from candidate c1 left join company c2 on c1.companyid
= c2.companyid where c1.companyid is null

Display count of employees without job:


SQL > select count(c1.candidat) as EmpCnt from candidate c1 left join company c2 on
c1.companyid = c2.companyid where c1.companyid is null

Display how many companies without employees:


SQL > select c1.CompanyId, c1.CompanyName from company c1 left join candidate c2 on
c1.CompanyId = c2.companyid where c2.companyid is null

Display count of companies without employees:


SQL > select count(c1.CompanyId) as CmpCnt from company c1 left join candidate c2 on
c1.CompanyId = c2.companyid where c2.companyid is null

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.

Table Name: account


Column Data Type
num NUMBER
name VARCHAR2(50)
balance NUMBER

Now, let's create the stored procedure to insert data into this table:

CREATE OR REPLACE PROCEDURE InsertIntoAccount (


p_num NUMBER,
p_name VARCHAR2,
p_balance NUMBER
)
IS
BEGIN
INSERT INTO account (num, name, balance)
VALUES (p_num, p_name, p_balance);

COMMIT;
END;
/

To execute this stored procedure, you can call it using PL/SQL:

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

Update balance in account:


Create the stored procedure to perform the deposit operation:

CREATE OR REPLACE PROCEDURE DepositAmount (


p_num NUMBER,
p_amount NUMBER
)
IS
v_current_balance NUMBER;
BEGIN
-- Retrieve the current balance for the given account number
SELECT balance INTO v_current_balance FROM account WHERE num = p_num;

-- Update the balance by adding the deposit amount


UPDATE account SET balance = v_current_balance + p_amount WHERE num = p_num;

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);

-- Deposit 1000 units into account number 2


DepositAmount(2, 1000);

-- Add more calls here for additional deposits


END;
/

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 155
Withdraw operation:

Table Name: account


Column Data Type
num NUMBER
name VARCHAR2(50)
balance NUMBER

let's create the stored procedure to perform the withdrawal operation:

CREATE OR REPLACE PROCEDURE WithdrawAmount (


p_num NUMBER,
p_amount NUMBER
)
IS
v_current_balance NUMBER;
BEGIN
-- Retrieve the current balance for the given account number
SELECT balance INTO v_current_balance FROM account WHERE num = p_num;

-- Check if there are sufficient funds for the withdrawal


IF v_current_balance >= p_amount THEN
-- Update the balance by subtracting the withdrawal amount
UPDATE account SET balance = v_current_balance - p_amount WHERE num = p_num;
COMMIT;
END IF;
END;
/

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);

-- Withdraw 800 units from account number 2


WithdrawAmount(2, 800);

-- Add more calls here for additional withdrawals


END;
/

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 156
Money Transfer from account to account:

CREATE OR REPLACE PROCEDURE MoneyTransfer (


p_from_account NUMBER,
p_to_account NUMBER,
p_amount NUMBER,
p_transfer_date DATE DEFAULT SYSDATE
)
IS
v_from_balance NUMBER;
v_to_balance NUMBER;
BEGIN
-- Retrieve the current balances for the from and to accounts
SELECT balance INTO v_from_balance FROM account WHERE num = p_from_account;
SELECT balance INTO v_to_balance FROM account WHERE num = p_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 find the current date-time.


SELECT SYSDATE FROM DUAL;

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';

Write an SQL query to join 3 tables.


SELECT column1, column2
FROM TableA
JOIN TableB ON TableA.Column3 = TableB.Column3
JOIN TableC ON TableA.Column4 = TableC.Column4;

Query to find Second Highest Salary of Employee?


Select distinct Salary from Employee e1 where 2=Select count(distinct Salary) from
Employee e2 where e1.salary<=e2.salary;

Query to find duplicate rows in table?


Select * from Employee a where row_id != select max(row_id) for Employee b where
a.Employee_num=b.Employee_num;

How to fetch monthly Salary of Employee if annual salary is given?


Select Employee_name,Salary/12 as ‘Monthly Salary’ from employee;

What is the Query to fetch first record from Employee table?


Select * from Employee where Rownum =1;

What is the Query to fetch last record from the table?


Select * from Employee where Rowid= select max(Rowid) from Employee;

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;

What is Query to display Nth Record from Employee table?


Select * from Employee where rownum = &n;

How to get 3 Highest salaries records from Employee table?


select distinct salary from employee a where 3 >= (select count(distinct salary) from
emp loyee b where a.salary <= b.salary) order by a.salary desc;

How to Display Odd rows in Employee table?


Select * from(Select rownum as rno,E.* from Employee E) where Mod(rno,2)=1;

How to Display Even rows in Employee table?


Select * from(Select rownum as rno,E.* from Employee) where Mod(rno,2)=0;

Display first 50% records from Employee table?


Select rownum,E.* from Employee E where rownum<=(Select count(*/2) from
Employee);

How do i fetch only common records between 2 tables?


Select * from Employee;
Intersect
Select * from Employee1;

Find Query to get information of Employee where Employee is not assigned to


the department.
Select * from Employee where Dept_no Not in(Select Department_no from
Employee);

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

What the difference is between TRUNCATE & DELETE command?


TRUNCATE removes all the rows but leaves the table structure intact. It cannot be
rolled back.
DELETE command can be rolled back.

What is meant by Joins?


Joins are used to extract data from multiple tables using some common columns or
conditions.

Differentiate Primary Key & a Unique Key?


Primary Key is used to identify each table row uniquely, while a Unique Key prevents
duplicate values in a table column.

What is the use of GROUP BY clause?


GROUP BY clause is used to identify and group the data by one or more columns in
the query results.

What are integrity constraints?


Integrity constraints prevent the entry of invalid data into the tables.
Examples Primary Key, Foreign Key, UNIQUE KEY, NOT NULL & CHECK.

Define aggregate function?


Aggregate functions perform summary operations on a set of values to provide a
single value.

Define UNION, UNION ALL, MINUS & INTERSECT


UNION operator returns all the rows from both the tables except the duplicate rows.
UNION ALL returns all the rows from both the tables along with the duplicate rows.
MINUS returns rows from the first table, which does not exist in the second table.
INTERSECT returns only the common rows in both the tables.

AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyd.
Page | 161

You might also like