SlideShare a Scribd company logo
Core Java Training
JDBC Contd.
Page 1Classification: Restricted
Agenda
• JDBC Continued
• Introduction to Java Enterprise Edition (Java EE)
Java & JEE Training
JDBC – Java Database Connectivity
Page 3Classification: Restricted
Introduction
• Data stored in variables and arrays is temporary
• It’s lost when a local variable goes out of scope or when the program
terminates
• For long-term retention of data, computers use files.
• Computers store files on secondary storage devices
• hard disks, optical disks, flash drives and magnetic tapes.
• Data maintained in files is persistent data because it exists beyond the
duration of program execution.
Page 4Classification: Restricted
Data Hierarchy
Page 5Classification: Restricted
Databases
• There are many ways to organize records in a file. The most common is
called a sequential file, in which records are stored in order by the record-
key field.
• A group of related files is called a database.
• A collection of programs designed to create and manage databases is called
a database management system (DBMS).
Page 6Classification: Restricted
JDBC – Java Database Connectivity
• Java JDBC is a Java API to connect and execute query with the database. JDBC
API uses JDBC drivers to connect with the database.
• Before JDBC, ODBC API was the database API to connect and execute query
with the database. But, ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured). That is why Java has defined
its own API (JDBC API) that uses JDBC drivers (written in Java language).
Page 7Classification: Restricted
JDBC Driver
• JDBC Driver is a software component that enables java application to
interact with the database.
Page 8Classification: Restricted
5 Steps to connect to the database in java
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
Page 9Classification: Restricted
5 Steps to connect to the database in java
1. Register the driver class
Class.forName("oracle.jdbc.driver.OracleDriver")
(throws ClassNotFoundException)
2. Creating connection –
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe");
(throws SQLException)
3. Creating statement:
Statement stmt=con.createStatement();
(throws SQLException)
4. Executing queries
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
(throws SQLException)
5. Closing connection
con.close(); // (throws SQLException)
Page 10Classification: Restricted
Working with Databases… Instruction.
• In our class, we will work with Oracle 11g XE (Express Edition).
• It is available for download for free from Oracle site:
http://www.oracle.com/technetwork/database/database-technologies/express-
edition/downloads/index.html
• Download the zip file, extract it, and run the setup file for installing Oracle database.
• Oracle database will get installed and use default port 1521.
• Then follow instructions here to complete the initial setup.
https://docs.oracle.com/cd/E17781_01/admin.112/e18585/toc.htm
• We will be working with the HR user/schema in all our examples.
o Unlock HR schema: ALTER USER HR ACCOUNT UNLOCK
o Specify a password for HR: ALTER USER HR IDENTIFIED BY <PASSWORD>
Page 11Classification: Restricted
HR USER / SCHEMA
• In Oracle, User and Schema mean the same.
Page 12Classification: Restricted
Demo of HR Schema
• Let us look at the Employees and Departments Tables.
• Basic CRUD operations syntax reference for SQL:
http://www.orafaq.com/wiki/CRUD
Page 13Classification: Restricted
Ojdbc6.jar
• Copy ojdbc6.jar from
C:oraclexeapporacleproduct11.2.0serverjdbclib
to your JRElibext folder.
• This has the JDBC driver you will need.
• Other way of doing is by adding the path to the jar file to your classpath
oTemporarily: Set classpath in commandline.
oPermanent: Add path of jar file to classpath environment variable.
Page 14Classification: Restricted
JDBC Example… Connecting to the database.
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 15Classification: Restricted
public static Connection getConnection(String url):
is used to establish the connection with the
specified url.
public static Connection getConnection(String
url,String userName,String password):
is used to establish the connection with the
specified url, username and password.
DriverManager class
• The DriverManager class acts as an interface between user and drivers. It
keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. The
DriverManager class maintains a list of Driver classes that have registered
themselves by calling the method DriverManager.registerDriver().
Page 16Classification: Restricted
Connection interface
• A Connection is the session between java application and database. The Connection interface
is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and DatabaseMetaData.
• The Connection interface provide many methods for transaction management like commit(),
rollback() etc.
• By default, connection commits the changes after executing queries.
• Commonly used methods:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int
resultSetConcurrency): Creates a Statement object that will generate ResultSet objects
with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By
default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Page 17Classification: Restricted
Statement interface
The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides
factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may
be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
Page 18Classification: Restricted
Example: Insert, Update and Delete using Statement.
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
Statement stmt=con.createStatement();
//stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");
//int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000
where id=33");
int result=stmt.executeUpdate("delete from emp765 where id=33");
System.out.println(result+" records affected");
con.close();
}}
Page 19Classification: Restricted
ResultSet interface
• The object of ResultSet maintains a cursor pointing to a row of a table.
Initially, cursor points to before the first row.
• By default, ResultSet object can be moved forward only and it is not
updatable.
• But we can make this object to move forward and backward direction by
passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as
updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSIT
IVE, ResultSet.CONCUR_UPDATABLE);
Page 20Classification: Restricted
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next
from the current position.
2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
3) public boolean first(): is used to move the cursor to the first row in
result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row
number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be
positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column
index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified column
name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column
index of the current row as String.
10) public String getString(String
columnName):
is used to return the data of specified column
name of the current row as String.
Page 21Classification: Restricted
Example of Scrollable ResultSet (retrieve data of 3rd row)
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}}
Page 22Classification: Restricted
PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
e.g. String sql="insert into emp values(?,?,?)";
• Protects against SQLInjection attacks.
Method Description
public void setInt(int paramIndex, int
value)
sets the integer value to the given
parameter index.
public void setString(int paramIndex,
String value)
sets the String value to the given
parameter index.
public void setFloat(int paramIndex, float
value)
sets the float value to the given parameter
index.
public void setDouble(int paramIndex,
double value)
sets the double value to the given
parameter index.
public int executeUpdate() executes the query. It is used for create,
drop, insert, update, delete etc.
public ResultSet executeQuery() executes the select query. It returns an
instance of ResultSet.
Page 23Classification: Restricted
Example of PreparedStatement interface that inserts the record
• create table emp(id number(10),name varchar2(50));
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 24Classification: Restricted
Example of PreparedStatement interface that updates the record
PreparedStatement stmt=con.prepareStatement("update emp set name=?
where id=?");
stmt.setString(1,”Pawan”);//the first parameter in the query (name)
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
Page 25Classification: Restricted
Example of PreparedStatement interface that deletes the record
PreparedStatement stmt=con.prepareStatement("delete from emp where
id=?");
stmt.setInt(1,101);
int i=stmt.executeUpdate();
System.out.println(i+" records deleted");
Page 26Classification: Restricted
Example of PreparedStatement interface that retrieve the records of a table
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Page 27Classification: Restricted
ResultSetMetaData Interface
• If you have to get metadata of a table like total number of column, column
name, column type etc. , ResultSetMetaData interface is useful because it
provides methods to get metadata from the ResultSet object.
Method Description
public int getColumnCount()throws
SQLException
it returns the total number of columns in
the ResultSet object.
public String getColumnName(int
index)throws SQLException
it returns the column name of the specified
column index.
public String getColumnTypeName(int
index)throws SQLException
it returns the column type name for the
specified index.
public String getTableName(int
index)throws SQLException
it returns the table name for the specified
column index.
Page 28Classification: Restricted
ResultSetMetaData example
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 29Classification: Restricted
DatabaseMetaData interface
• DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.
• Commonly used methods:
o public String getDriverName()throws SQLException: it returns the name of the JDBC
driver.
o public String getDriverVersion()throws SQLException: it returns the version number of
the JDBC driver.
o public String getUserName()throws SQLException: it returns the username of the
database.
o public String getDatabaseProductName()throws SQLException: it returns the product
name of the database.
o public String getDatabaseProductVersion()throws SQLException: it returns the product
version of the database.
o public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description of the
tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE,
SYNONYM etc.
Page 30Classification: Restricted
Example of DatabaseMetaData interface
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver Name: "+dbmd.getDriverName());
System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 31Classification: Restricted
DatabaseMetaData interface that prints all table names
import java.sql.*;
class Dbmd2{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 32Classification: Restricted
DatabaseMetaData interface that prints total number of views
import java.sql.*;
class Dbmd3{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"VIEW"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Page 33Classification: Restricted
Example of storing image into Database
CREATE TABLE "IMGTABLE"
( "NAME" VARCHAR2(4000),
"PHOTO" BLOB
)
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1,“Pawan");
FileInputStream fin=new FileInputStream("d:g.jpg");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
Page 34Classification: Restricted
Retrieving image from Oracle database
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from imgtable");
ResultSet rs=ps.executeQuery();
if(rs.next()){//now on 1st row
Blob b=rs.getBlob(2);//2 means 2nd column data
byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
FileOutputStream fout=new FileOutputStream("d:sonoo.jpg");
fout.write(barr);
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
Page 35Classification: Restricted
Storing file in a database
import java.io.*;
import java.sql.*;
public class StoreFile {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"insert into filetable values(?,?)");
File f=new File("d:myfile.txt");
FileReader fr=new FileReader(f);
ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
Page 36Classification: Restricted
Retrieve file from database
import java.io.*;
import java.sql.*;
public class RetrieveFile {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from filetable");
ResultSet rs=ps.executeQuery();
rs.next();//now on 1st row
Clob c=rs.getClob(2);
Reader r=c.getCharacterStream();
FileWriter fw=new FileWriter("d:retrivefile.txt");
int i;
while((i=r.read())!=-1)
fw.write((char)i);
fw.close();
con.close();
System.out.println("success");
}catch (Exception e) {e.printStackTrace(); }
}
}
Page 37Classification: Restricted
CallableStatement Interface
• CallableStatement interface is used to call the stored procedures and
functions.
• We can have business logic on the database by the use of stored
procedures and functions that will make the performance better because
these are precompiled.
• Suppose you need the get the age of the employee based on the date of
birth, you may create a function that receives date as the input and returns
age of the employee as the output.
Page 38Classification: Restricted
How to get the instance of CallableStatement?
CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
Page 39Classification: Restricted
Stored Procedure example
create table myuser(id number(10), name varchar2(200));
create or replace procedure "INSERTR"
(id IN NUMBER, name IN VARCHAR2)
is
begin
insert into myuser values(id,name);
end;
Page 40Classification: Restricted
Calling procedure from JDBC Example
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();
System.out.println("success");
}
}
Page 41Classification: Restricted
Function example…
create or replace function sum4
(n1 in number,n2 in number)
return number
is
temp number(8);
begin
temp :=n1+n2;
return temp;
end;
Page 42Classification: Restricted
Calling function from JDBC Example
import java.sql.*;
public class FuncSum {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}");
stmt.setInt(2,10);
stmt.setInt(3,43);
stmt.registerOutParameter(1,Types.INTEGER);
stmt.execute();
System.out.println(stmt.getInt(1));
}
}
Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc.
Page 43Classification: Restricted
Transaction Management in JDBC
• Transaction represents a single unit of work.
• ACID properties:
1. Atomicity means either all successful or none.
2. Consistency ensures bringing the database from one consistent state
to another consistent state.
3. Isolation ensures that transaction is isolated from other transaction.
4. Durability means once a transaction has been committed, it will
remain so, even in the event of errors, power loss etc.
Page 44Classification: Restricted
Commit and rollback
Page 45Classification: Restricted
Transaction management using JDBC
Method Description
void setAutoCommit(boolean
status)
It is true by default means each
transaction is committed by
default.
void commit() commits the transaction.
void rollback() cancels the transaction.
In JDBC, Connection interface provides methods to manage transaction.
Page 46Classification: Restricted
Example of transaction management
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste
m","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
con.commit();
con.close();
}}
Page 47Classification: Restricted
Batch Processing in JDBC
•Instead of executing a single query, we can execute a batch
(group) of queries. It makes the performance fast.
•The java.sql.Statement and java.sql.PreparedStatement
interfaces provide methods for batch processing.
Method Description
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.
Page 48Classification: Restricted
Batch Processing example using Statement
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"
);
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into myuser values(190,'abhi',40000)");
stmt.addBatch("insert into myuser values(191,'umesh',50000)");
stmt.executeBatch();//executing the batch
con.commit();
con.close();
}}
Page 49Classification: Restricted
Exercise
Write a batch processing program using PreparedStatement to update
multiple values entered by the user.
Page 50Classification: Restricted
JDBC RowSet (Introduced in JDK 5)
• Wrapper of ResultSet.
• Easy and flexible to use
• It is Scrollable and Updatable by default
Page 51Classification: Restricted
RowSet example
public class RowSetExample {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
//Creating and Executing RowSet
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("system");
rowSet.setPassword("oracle");
rowSet.setCommand("select * from emp400");
rowSet.execute();
while (rowSet.next()) {
// Generating cursor Moved event
System.out.println("Id: " + rowSet.getString(1));
System.out.println("Name: " + rowSet.getString(2));
System.out.println("Salary: " + rowSet.getString(3));
}
}
}
Page 52Classification: Restricted
Re-look at the Java Major Editions
Page 53Classification: Restricted
Application Servers
• In the beginning, there was darkness and cold. Then, …
Centralized, non-distributed
Page 54Classification: Restricted
Application Servers
• In the 90’s, systems should be client-server
Page 55Classification: Restricted
Application Servers
• Today, enterprise applications use the multi-tier model
Page 56Classification: Restricted
Application Servers
• “Multi-tier applications” have several independent components
• An application server provides the infrastructure and services to run such
applications
Page 57Classification: Restricted
Application Servers
• Application server products can be separated into 3 categories:
• JEE-based solutions
• Non-JEE solutions (PHP, ColdFusion, Perl, etc.)
• And the Microsoft solution (ASP/COM and now .NET with ASP.NET,
VB.NET, C#, etc.)
Page 58Classification: Restricted
J2EE Application Servers
• Major J2EE products:
• BEA WebLogic
• IBM WebSphere
• Sun iPlanet Application Server
• Oracle 9iAS
• HP/Bluestone Total-e-Server
• Borland AppServer
• JBoss (free open source)
Page 59Classification: Restricted
Web Server and Application Server
Page 60Classification: Restricted
What is JEE?
• It is a public specification that embodies several technologies
• Current version is JEE 6
• J2EE defines a model for developing multi-tier, web based, enterprise
applications with distributed components
• Benefits:
oHigh availability
oScalability
oIntegration with existing systems
oFreedom to choose vendors of application servers, tools, components
oMulti-platform
Page 61Classification: Restricted
Main technologies
• JavaServer Pages (JSP)
• Servlet
• Enterprise JavaBeans (EJB)
• Java Server Faces (JSF) – Not covered in this course.
Page 62Classification: Restricted
Enterprise Java – Multi-tier architecture
Page 63Classification: Restricted
JSP
• Used for web pages with dynamic content
• Processes HTTP requests (non-blocking call-and-return)
• Accepts HTML tags, special JSP tags, and scriptlets of Java code
• Separates static content from presentation logic
• Can be created by web designer using HTML tools
Page 64Classification: Restricted
Servlet
• Used for web pages with dynamic content
• Processes HTTP requests (non-blocking call-and-return)
• Written in Java; uses print statements to render HTML
• Loaded into memory once and then called many times
• Provides APIs for session management
Page 65Classification: Restricted
EJB
• EJBs are distributed components used to implement business logic (no UI)
• Developer concentrates on business logic
• Availability, scalability, security, interoperability and integrability handled by
the J2EE server
• Client of EJBs can be JSPs, servlets, other EJBs and external aplications
• Clients see interfaces
Page 66Classification: Restricted
Thank you!

More Related Content

PPSX
PPSX
Hibernate - Part 1
PPSX
Java IO, Serialization
PPTX
Session 24 - JDBC, Intro to Enterprise Java
PPSX
Spring - Part 3 - AOP
PPSX
Hibernate - Part 2
PPTX
Session 22 - Java IO, Serialization
PPTX
Session 23 - JDBC
Hibernate - Part 1
Java IO, Serialization
Session 24 - JDBC, Intro to Enterprise Java
Spring - Part 3 - AOP
Hibernate - Part 2
Session 22 - Java IO, Serialization
Session 23 - JDBC

What's hot (19)

PPTX
Spring data jpa
PDF
Hibernate Interview Questions
PPSX
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
ODP
Hibernate Developer Reference
PPTX
Hibernate tutorial
PPTX
Hibernate in Action
PPSX
OOP with Java - Continued
PPSX
Elements of Java Language
PPS
Java Hibernate Programming with Architecture Diagram and Example
PPT
Hibernate presentation
PPSX
OOP with Java - Part 3
PDF
22jdbc
PPTX
Hibernate
DOC
Hibernate tutorial for beginners
PDF
Data access
PDF
Hibernate 3
PPTX
Hibernate ppt
PPTX
Session 38 - Core Java (New Features) - Part 1
Spring data jpa
Hibernate Interview Questions
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hibernate Developer Reference
Hibernate tutorial
Hibernate in Action
OOP with Java - Continued
Elements of Java Language
Java Hibernate Programming with Architecture Diagram and Example
Hibernate presentation
OOP with Java - Part 3
22jdbc
Hibernate
Hibernate tutorial for beginners
Data access
Hibernate 3
Hibernate ppt
Session 38 - Core Java (New Features) - Part 1
Ad

Similar to JDBC Part - 2 (20)

PPTX
Database connect
PDF
Introduction to JDBC and database access in web applications
PPTX
Java Database Connectivity with 5 Steps.pptx
PDF
Jdbc[1]
PDF
JDBC programming
PDF
Lecture17
PPT
Jdbc
PDF
PPTX
PPTX
Advance Java Programming (CM5I)5.Interacting with-database
PDF
Core Java Programming Language (JSE) : Chapter XIII - JDBC
PPTX
Jdbc
PDF
Jdbc tutorial
PPTX
Java database connectivity
PPTX
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
PPT
jdbc_presentation.ppt
PDF
PPT
JDBC Connecticity.ppt
Database connect
Introduction to JDBC and database access in web applications
Java Database Connectivity with 5 Steps.pptx
Jdbc[1]
JDBC programming
Lecture17
Jdbc
Advance Java Programming (CM5I)5.Interacting with-database
Core Java Programming Language (JSE) : Chapter XIII - JDBC
Jdbc
Jdbc tutorial
Java database connectivity
21CS642 Module 5 JDBC PPT.pptx VI SEM CSE Students
jdbc_presentation.ppt
JDBC Connecticity.ppt
Ad

More from Hitesh-Java (20)

PPSX
Spring - Part 4 - Spring MVC
PPSX
Spring - Part 1 - IoC, Di and Beans
PPSX
JSP - Part 2 (Final)
PPSX
JSP - Part 1
PPSX
Struts 2 - Hibernate Integration
PPSX
Struts 2 - Introduction
PPSX
Inner Classes
PPSX
Collections - Maps
PPSX
Review Session - Part -2
PPSX
Review Session and Attending Java Interviews
PPSX
Collections - Lists, Sets
PPSX
Collections - Sorting, Comparing Basics
PPSX
Collections - Array List
PPSX
Object Class
PPSX
Exception Handling - Continued
PPSX
Exception Handling - Part 1
PPSX
OOPs with Java - Packaging and Access Modifiers
PPSX
OOP with Java - Abstract Classes and Interfaces
PPSX
Intro to Object Oriented Programming with Java
PPSX
Practice Session
Spring - Part 4 - Spring MVC
Spring - Part 1 - IoC, Di and Beans
JSP - Part 2 (Final)
JSP - Part 1
Struts 2 - Hibernate Integration
Struts 2 - Introduction
Inner Classes
Collections - Maps
Review Session - Part -2
Review Session and Attending Java Interviews
Collections - Lists, Sets
Collections - Sorting, Comparing Basics
Collections - Array List
Object Class
Exception Handling - Continued
Exception Handling - Part 1
OOPs with Java - Packaging and Access Modifiers
OOP with Java - Abstract Classes and Interfaces
Intro to Object Oriented Programming with Java
Practice Session

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Cloud computing and distributed systems.
PPTX
Big Data Technologies - Introduction.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
The AUB Centre for AI in Media Proposal.docx
Digital-Transformation-Roadmap-for-Companies.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Cloud computing and distributed systems.
Big Data Technologies - Introduction.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Programs and apps: productivity, graphics, security and other tools
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
sap open course for s4hana steps from ECC to s4
Agricultural_Statistics_at_a_Glance_2022_0.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Per capita expenditure prediction using model stacking based on satellite ima...
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation_ Review paper, used for researhc scholars
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx

JDBC Part - 2

  • 2. Page 1Classification: Restricted Agenda • JDBC Continued • Introduction to Java Enterprise Edition (Java EE)
  • 3. Java & JEE Training JDBC – Java Database Connectivity
  • 4. Page 3Classification: Restricted Introduction • Data stored in variables and arrays is temporary • It’s lost when a local variable goes out of scope or when the program terminates • For long-term retention of data, computers use files. • Computers store files on secondary storage devices • hard disks, optical disks, flash drives and magnetic tapes. • Data maintained in files is persistent data because it exists beyond the duration of program execution.
  • 6. Page 5Classification: Restricted Databases • There are many ways to organize records in a file. The most common is called a sequential file, in which records are stored in order by the record- key field. • A group of related files is called a database. • A collection of programs designed to create and manage databases is called a database management system (DBMS).
  • 7. Page 6Classification: Restricted JDBC – Java Database Connectivity • Java JDBC is a Java API to connect and execute query with the database. JDBC API uses JDBC drivers to connect with the database. • Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
  • 8. Page 7Classification: Restricted JDBC Driver • JDBC Driver is a software component that enables java application to interact with the database.
  • 9. Page 8Classification: Restricted 5 Steps to connect to the database in java 1. Register the driver class 2. Creating connection 3. Creating statement 4. Executing queries 5. Closing connection
  • 10. Page 9Classification: Restricted 5 Steps to connect to the database in java 1. Register the driver class Class.forName("oracle.jdbc.driver.OracleDriver") (throws ClassNotFoundException) 2. Creating connection – Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","password"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe"); (throws SQLException) 3. Creating statement: Statement stmt=con.createStatement(); (throws SQLException) 4. Executing queries ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); } (throws SQLException) 5. Closing connection con.close(); // (throws SQLException)
  • 11. Page 10Classification: Restricted Working with Databases… Instruction. • In our class, we will work with Oracle 11g XE (Express Edition). • It is available for download for free from Oracle site: http://www.oracle.com/technetwork/database/database-technologies/express- edition/downloads/index.html • Download the zip file, extract it, and run the setup file for installing Oracle database. • Oracle database will get installed and use default port 1521. • Then follow instructions here to complete the initial setup. https://docs.oracle.com/cd/E17781_01/admin.112/e18585/toc.htm • We will be working with the HR user/schema in all our examples. o Unlock HR schema: ALTER USER HR ACCOUNT UNLOCK o Specify a password for HR: ALTER USER HR IDENTIFIED BY <PASSWORD>
  • 12. Page 11Classification: Restricted HR USER / SCHEMA • In Oracle, User and Schema mean the same.
  • 13. Page 12Classification: Restricted Demo of HR Schema • Let us look at the Employees and Departments Tables. • Basic CRUD operations syntax reference for SQL: http://www.orafaq.com/wiki/CRUD
  • 14. Page 13Classification: Restricted Ojdbc6.jar • Copy ojdbc6.jar from C:oraclexeapporacleproduct11.2.0serverjdbclib to your JRElibext folder. • This has the JDBC driver you will need. • Other way of doing is by adding the path to the jar file to your classpath oTemporarily: Set classpath in commandline. oPermanent: Add path of jar file to classpath environment variable.
  • 15. Page 14Classification: Restricted JDBC Example… Connecting to the database. import java.sql.*; class OracleCon{ public static void main(String args[]){ try{ //step1 load the driver class Class.forName("oracle.jdbc.driver.OracleDriver"); //step2 create the connection object Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); //step3 create the statement object Statement stmt=con.createStatement(); //step4 execute query ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)); //step5 close the connection object con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 16. Page 15Classification: Restricted public static Connection getConnection(String url): is used to establish the connection with the specified url. public static Connection getConnection(String url,String userName,String password): is used to establish the connection with the specified url, username and password. DriverManager class • The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().
  • 17. Page 16Classification: Restricted Connection interface • A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. • The Connection interface provide many methods for transaction management like commit(), rollback() etc. • By default, connection commits the changes after executing queries. • Commonly used methods: 1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries. 2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object that will generate ResultSet objects with the given type and concurrency. 3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true. 4) public void commit(): saves the changes made since the previous commit/rollback permanent. 5) public void rollback(): Drops all changes made since the previous commit/rollback. 6) public void close(): closes the connection and Releases a JDBC resources immediately.
  • 18. Page 17Classification: Restricted Statement interface The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet. 1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. 3) public boolean execute(String sql): is used to execute queries that may return multiple results. 4) public int[] executeBatch(): is used to execute batch of commands.
  • 19. Page 18Classification: Restricted Example: Insert, Update and Delete using Statement. import java.sql.*; class FetchRecord{ public static void main(String args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste m","oracle"); Statement stmt=con.createStatement(); //stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)"); //int result=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000 where id=33"); int result=stmt.executeUpdate("delete from emp765 where id=33"); System.out.println(result+" records affected"); con.close(); }}
  • 20. Page 19Classification: Restricted ResultSet interface • The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row. • By default, ResultSet object can be moved forward only and it is not updatable. • But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSIT IVE, ResultSet.CONCUR_UPDATABLE);
  • 21. Page 20Classification: Restricted Commonly used methods of ResultSet interface 1) public boolean next(): is used to move the cursor to the one row next from the current position. 2) public boolean previous(): is used to move the cursor to the one row previous from the current position. 3) public boolean first(): is used to move the cursor to the first row in result set object. 4) public boolean last(): is used to move the cursor to the last row in result set object. 5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object. 6) public boolean relative(int row): is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. 7) public int getInt(int columnIndex): is used to return the data of specified column index of the current row as int. 8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int. 9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String. 10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
  • 22. Page 21Classification: Restricted Example of Scrollable ResultSet (retrieve data of 3rd row) import java.sql.*; class FetchRecord{ public static void main(String args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs=stmt.executeQuery("select * from emp765"); //getting the record of 3rd row rs.absolute(3); System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); con.close(); }}
  • 23. Page 22Classification: Restricted PreparedStatement interface • The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. e.g. String sql="insert into emp values(?,?,?)"; • Protects against SQLInjection attacks. Method Description public void setInt(int paramIndex, int value) sets the integer value to the given parameter index. public void setString(int paramIndex, String value) sets the String value to the given parameter index. public void setFloat(int paramIndex, float value) sets the float value to the given parameter index. public void setDouble(int paramIndex, double value) sets the double value to the given parameter index. public int executeUpdate() executes the query. It is used for create, drop, insert, update, delete etc. public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet.
  • 24. Page 23Classification: Restricted Example of PreparedStatement interface that inserts the record • create table emp(id number(10),name varchar2(50)); import java.sql.*; class InsertPrepared{ public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)"); stmt.setInt(1,101);//1 specifies the first parameter in the query stmt.setString(2,"Ratan"); int i=stmt.executeUpdate(); System.out.println(i+" records inserted"); con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 25. Page 24Classification: Restricted Example of PreparedStatement interface that updates the record PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?"); stmt.setString(1,”Pawan”);//the first parameter in the query (name) stmt.setInt(2,101); int i=stmt.executeUpdate(); System.out.println(i+" records updated");
  • 26. Page 25Classification: Restricted Example of PreparedStatement interface that deletes the record PreparedStatement stmt=con.prepareStatement("delete from emp where id=?"); stmt.setInt(1,101); int i=stmt.executeUpdate(); System.out.println(i+" records deleted");
  • 27. Page 26Classification: Restricted Example of PreparedStatement interface that retrieve the records of a table PreparedStatement stmt=con.prepareStatement("select * from emp"); ResultSet rs=stmt.executeQuery(); while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
  • 28. Page 27Classification: Restricted ResultSetMetaData Interface • If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object. Method Description public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index. public String getTableName(int index)throws SQLException it returns the table name for the specified column index.
  • 29. Page 28Classification: Restricted ResultSetMetaData example import java.sql.*; class Rsmd{ public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.prepareStatement("select * from emp"); ResultSet rs=ps.executeQuery(); ResultSetMetaData rsmd=rs.getMetaData(); System.out.println("Total columns: "+rsmd.getColumnCount()); System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1)); System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 30. Page 29Classification: Restricted DatabaseMetaData interface • DatabaseMetaData interface provides methods to get meta data of a database such as database product name, database product version, driver name, name of total number of tables, name of total number of views etc. • Commonly used methods: o public String getDriverName()throws SQLException: it returns the name of the JDBC driver. o public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver. o public String getUserName()throws SQLException: it returns the username of the database. o public String getDatabaseProductName()throws SQLException: it returns the product name of the database. o public String getDatabaseProductVersion()throws SQLException: it returns the product version of the database. o public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)throws SQLException: it returns the description of the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
  • 31. Page 30Classification: Restricted Example of DatabaseMetaData interface import java.sql.*; class Dbmd{ public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); DatabaseMetaData dbmd=con.getMetaData(); System.out.println("Driver Name: "+dbmd.getDriverName()); System.out.println("Driver Version: "+dbmd.getDriverVersion()); System.out.println("UserName: "+dbmd.getUserName()); System.out.println("Database Product Name: "+dbmd.getDatabaseProductName()); System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion()); con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 32. Page 31Classification: Restricted DatabaseMetaData interface that prints all table names import java.sql.*; class Dbmd2{ public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); DatabaseMetaData dbmd=con.getMetaData(); String table[]={"TABLE"}; ResultSet rs=dbmd.getTables(null,null,null,table); while(rs.next()){ System.out.println(rs.getString(3)); } con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 33. Page 32Classification: Restricted DatabaseMetaData interface that prints total number of views import java.sql.*; class Dbmd3{ public static void main(String args[]){ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); DatabaseMetaData dbmd=con.getMetaData(); String table[]={"VIEW"}; ResultSet rs=dbmd.getTables(null,null,null,table); while(rs.next()){ System.out.println(rs.getString(3)); } con.close(); }catch(Exception e){ System.out.println(e);} } }
  • 34. Page 33Classification: Restricted Example of storing image into Database CREATE TABLE "IMGTABLE" ( "NAME" VARCHAR2(4000), "PHOTO" BLOB ) import java.sql.*; import java.io.*; public class InsertImage { public static void main(String[] args) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)"); ps.setString(1,“Pawan"); FileInputStream fin=new FileInputStream("d:g.jpg"); ps.setBinaryStream(2,fin,fin.available()); int i=ps.executeUpdate(); System.out.println(i+" records affected"); con.close(); }catch (Exception e) {e.printStackTrace();} } }
  • 35. Page 34Classification: Restricted Retrieving image from Oracle database import java.sql.*; import java.io.*; public class RetrieveImage { public static void main(String[] args) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.prepareStatement("select * from imgtable"); ResultSet rs=ps.executeQuery(); if(rs.next()){//now on 1st row Blob b=rs.getBlob(2);//2 means 2nd column data byte barr[]=b.getBytes(1,(int)b.length());//1 means first image FileOutputStream fout=new FileOutputStream("d:sonoo.jpg"); fout.write(barr); fout.close(); }//end of if System.out.println("ok"); con.close(); }catch (Exception e) {e.printStackTrace(); } } }
  • 36. Page 35Classification: Restricted Storing file in a database import java.io.*; import java.sql.*; public class StoreFile { public static void main(String[] args) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.prepareStatement( "insert into filetable values(?,?)"); File f=new File("d:myfile.txt"); FileReader fr=new FileReader(f); ps.setInt(1,101); ps.setCharacterStream(2,fr,(int)f.length()); int i=ps.executeUpdate(); System.out.println(i+" records affected"); con.close(); }catch (Exception e) {e.printStackTrace();} } }
  • 37. Page 36Classification: Restricted Retrieve file from database import java.io.*; import java.sql.*; public class RetrieveFile { public static void main(String[] args) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); PreparedStatement ps=con.prepareStatement("select * from filetable"); ResultSet rs=ps.executeQuery(); rs.next();//now on 1st row Clob c=rs.getClob(2); Reader r=c.getCharacterStream(); FileWriter fw=new FileWriter("d:retrivefile.txt"); int i; while((i=r.read())!=-1) fw.write((char)i); fw.close(); con.close(); System.out.println("success"); }catch (Exception e) {e.printStackTrace(); } } }
  • 38. Page 37Classification: Restricted CallableStatement Interface • CallableStatement interface is used to call the stored procedures and functions. • We can have business logic on the database by the use of stored procedures and functions that will make the performance better because these are precompiled. • Suppose you need the get the age of the employee based on the date of birth, you may create a function that receives date as the input and returns age of the employee as the output.
  • 39. Page 38Classification: Restricted How to get the instance of CallableStatement? CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
  • 40. Page 39Classification: Restricted Stored Procedure example create table myuser(id number(10), name varchar2(200)); create or replace procedure "INSERTR" (id IN NUMBER, name IN VARCHAR2) is begin insert into myuser values(id,name); end;
  • 41. Page 40Classification: Restricted Calling procedure from JDBC Example import java.sql.*; public class Proc { public static void main(String[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); CallableStatement stmt=con.prepareCall("{call insertR(?,?)}"); stmt.setInt(1,1011); stmt.setString(2,"Amit"); stmt.execute(); System.out.println("success"); } }
  • 42. Page 41Classification: Restricted Function example… create or replace function sum4 (n1 in number,n2 in number) return number is temp number(8); begin temp :=n1+n2; return temp; end;
  • 43. Page 42Classification: Restricted Calling function from JDBC Example import java.sql.*; public class FuncSum { public static void main(String[] args) throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); CallableStatement stmt=con.prepareCall("{?= call sum4(?,?)}"); stmt.setInt(2,10); stmt.setInt(3,43); stmt.registerOutParameter(1,Types.INTEGER); stmt.execute(); System.out.println(stmt.getInt(1)); } } Types class defines many constants such as INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc.
  • 44. Page 43Classification: Restricted Transaction Management in JDBC • Transaction represents a single unit of work. • ACID properties: 1. Atomicity means either all successful or none. 2. Consistency ensures bringing the database from one consistent state to another consistent state. 3. Isolation ensures that transaction is isolated from other transaction. 4. Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.
  • 46. Page 45Classification: Restricted Transaction management using JDBC Method Description void setAutoCommit(boolean status) It is true by default means each transaction is committed by default. void commit() commits the transaction. void rollback() cancels the transaction. In JDBC, Connection interface provides methods to manage transaction.
  • 47. Page 46Classification: Restricted Example of transaction management import java.sql.*; class FetchRecords{ public static void main(String args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","syste m","oracle"); con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.executeUpdate("insert into user420 values(190,'abhi',40000)"); stmt.executeUpdate("insert into user420 values(191,'umesh',50000)"); con.commit(); con.close(); }}
  • 48. Page 47Classification: Restricted Batch Processing in JDBC •Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast. •The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing. Method Description void addBatch(String query) It adds query into batch. int[] executeBatch() It executes the batch of queries.
  • 49. Page 48Classification: Restricted Batch Processing example using Statement import java.sql.*; class FetchRecords{ public static void main(String args[])throws Exception{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle" ); con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.addBatch("insert into myuser values(190,'abhi',40000)"); stmt.addBatch("insert into myuser values(191,'umesh',50000)"); stmt.executeBatch();//executing the batch con.commit(); con.close(); }}
  • 50. Page 49Classification: Restricted Exercise Write a batch processing program using PreparedStatement to update multiple values entered by the user.
  • 51. Page 50Classification: Restricted JDBC RowSet (Introduced in JDK 5) • Wrapper of ResultSet. • Easy and flexible to use • It is Scrollable and Updatable by default
  • 52. Page 51Classification: Restricted RowSet example public class RowSetExample { public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); //Creating and Executing RowSet JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet(); rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe"); rowSet.setUsername("system"); rowSet.setPassword("oracle"); rowSet.setCommand("select * from emp400"); rowSet.execute(); while (rowSet.next()) { // Generating cursor Moved event System.out.println("Id: " + rowSet.getString(1)); System.out.println("Name: " + rowSet.getString(2)); System.out.println("Salary: " + rowSet.getString(3)); } } }
  • 53. Page 52Classification: Restricted Re-look at the Java Major Editions
  • 54. Page 53Classification: Restricted Application Servers • In the beginning, there was darkness and cold. Then, … Centralized, non-distributed
  • 55. Page 54Classification: Restricted Application Servers • In the 90’s, systems should be client-server
  • 56. Page 55Classification: Restricted Application Servers • Today, enterprise applications use the multi-tier model
  • 57. Page 56Classification: Restricted Application Servers • “Multi-tier applications” have several independent components • An application server provides the infrastructure and services to run such applications
  • 58. Page 57Classification: Restricted Application Servers • Application server products can be separated into 3 categories: • JEE-based solutions • Non-JEE solutions (PHP, ColdFusion, Perl, etc.) • And the Microsoft solution (ASP/COM and now .NET with ASP.NET, VB.NET, C#, etc.)
  • 59. Page 58Classification: Restricted J2EE Application Servers • Major J2EE products: • BEA WebLogic • IBM WebSphere • Sun iPlanet Application Server • Oracle 9iAS • HP/Bluestone Total-e-Server • Borland AppServer • JBoss (free open source)
  • 60. Page 59Classification: Restricted Web Server and Application Server
  • 61. Page 60Classification: Restricted What is JEE? • It is a public specification that embodies several technologies • Current version is JEE 6 • J2EE defines a model for developing multi-tier, web based, enterprise applications with distributed components • Benefits: oHigh availability oScalability oIntegration with existing systems oFreedom to choose vendors of application servers, tools, components oMulti-platform
  • 62. Page 61Classification: Restricted Main technologies • JavaServer Pages (JSP) • Servlet • Enterprise JavaBeans (EJB) • Java Server Faces (JSF) – Not covered in this course.
  • 63. Page 62Classification: Restricted Enterprise Java – Multi-tier architecture
  • 64. Page 63Classification: Restricted JSP • Used for web pages with dynamic content • Processes HTTP requests (non-blocking call-and-return) • Accepts HTML tags, special JSP tags, and scriptlets of Java code • Separates static content from presentation logic • Can be created by web designer using HTML tools
  • 65. Page 64Classification: Restricted Servlet • Used for web pages with dynamic content • Processes HTTP requests (non-blocking call-and-return) • Written in Java; uses print statements to render HTML • Loaded into memory once and then called many times • Provides APIs for session management
  • 66. Page 65Classification: Restricted EJB • EJBs are distributed components used to implement business logic (no UI) • Developer concentrates on business logic • Availability, scalability, security, interoperability and integrability handled by the J2EE server • Client of EJBs can be JSPs, servlets, other EJBs and external aplications • Clients see interfaces