0% found this document useful (0 votes)
79 views

DR - Poorna Chandra S

This document provides an overview of Java Database Connectivity (JDBC) including defining JDBC, the different JDBC drivers, and the basic 5 steps to connect to a database using JDBC: 1) register the driver class, 2) create a connection, 3) create a statement, 4) execute queries, and 5) close the connection. It also discusses some key JDBC interfaces like Connection, Statement, and ResultSet.

Uploaded by

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

DR - Poorna Chandra S

This document provides an overview of Java Database Connectivity (JDBC) including defining JDBC, the different JDBC drivers, and the basic 5 steps to connect to a database using JDBC: 1) register the driver class, 2) create a connection, 3) create a statement, 4) execute queries, and 5) close the connection. It also discusses some key JDBC interfaces like Connection, Statement, and ResultSet.

Uploaded by

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

JDBC

Dr.Poorna Chandra S PhD

Associate Professor,Dept. of MCA, East West Institute of


Technology,Bengaluru(Affiliated to VTU,Belagavi.)

January 7, 2023

Dr.Poorna Chandra S PhD JDBC


Outline
Define JDBC ? Why should we use JDBC ?
Deifne API ?
JDBC Drivers
5 Steps to connect to the Database
Connectivity with Oracle using JDBC
Connectivity with MySQL using JDBC
DriverManager class
Connection interface
Statement interface
ResultSet interface
PreparedStatement Interface
ResultSetMetaData interface
DatabaseMetaData interface
Storing image in Oracle
Retrieving image from Oracle
Storing file in Oracle
Dr.Poorna Chandra S PhD JDBC
JDBC I
What is JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java
API to connect and execute the query with the database. It is
a part of JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database.
There are four types of JDBC drivers:
1 JDBC-ODBC Bridge Driver
2 Native Driver
3 Network Protocol Driver
4 Thin Driver

We can use JDBC API to access tabular data stored in any


relational database.

Dr.Poorna Chandra S PhD JDBC


JDBC II
By the help of JDBC API, we can save, update, delete and
fetch data from the database. It is like Open Database
Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release


since 21st September, 2017. It is based on the X/Open SQL
Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API.
A list of popular interfaces of JDBC API are given
below:

Dr.Poorna Chandra S PhD JDBC


JDBC III
1 Driver interface
2 Connection interface
3 Statement interface
4 PreparedStatement interface
5 CallableStatement interface
6 ResultSet interface
7 ResultSetMetaData interface
8 DatabaseMetaData interface
9 RowSet interface

A list of popular classes of JDBC API are given below:

1 DriverManager class
2 Blob class
Dr.Poorna Chandra S PhD JDBC
JDBC IV
3 Clob class
4 Types class

Why Should We Use JDBC ?


Before JDBC, ODBC API was the database API to connect
and execute the 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).
We can use JDBC API to handle database using Java
program and can perform the following activities:

1 Connect to the database


2 Execute queries and update statements to the database
Dr.Poorna Chandra S PhD JDBC
JDBC V

3 Retrieve the result received from the database.

What is API
API (Application programming interface) is a document that
contains a description of all the features of a product or
software. It represents classes and interfaces that software
programs can follow to communicate with each other. An API
can be created for applications, libraries, operating systems,
etc.

Dr.Poorna Chandra S PhD JDBC


JDBC Driver I

JDBC Driver is a software component that enables java


application to interact with the database.
There are 4 types of JDBC drivers:

1 JDBC-ODBC bridge driver


2 Native-API driver (partially java driver)
3 Network Protocol driver (fully java driver)
4 Thin driver (fully java driver)

Dr.Poorna Chandra S PhD JDBC


JDBC Driver II

1 JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to
connect to the database.
The JDBC-ODBC bridge driver converts JDBC method
calls into the ODBC function calls. This is now
discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from
Java 8. Oracle recommends that you use JDBC drivers
provided by the vendor of your database instead of the

Dr.Poorna Chandra S PhD JDBC


JDBC Driver III
JDBC-ODBC Bridge.

Advantages
easy to use
can be easily connected to any database
Disadvantages
Dr.Poorna Chandra S PhD JDBC
JDBC Driver IV

Performance degraded because JDBC method call is


converted into the ODBC function calls.
The ODBC driver needs to be installed on the client
machine.
2 Native-API driver
The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely
in java.

Dr.Poorna Chandra S PhD JDBC


JDBC Driver V

Advantages
performance upgraded than JDBC-ODBC bridge driver
Disadvanatages
The Native driver needs to be installed on the each
client machine.
Dr.Poorna Chandra S PhD JDBC
JDBC Driver VI

The Vendor client library needs to be installed on client


machine.
3 Network Protocol driver
The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into
the vendor-specific database protocol. It is fully written in
java.

Dr.Poorna Chandra S PhD JDBC


JDBC Driver VII

Advantages
No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.

Dr.Poorna Chandra S PhD JDBC


JDBC Driver VIII

Disadvantages
Network support is required on client machine.
Requires database-specific coding to be done in the
middle tier.
Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done
in the middle tier.
4 Thin driver
The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Dr.Poorna Chandra S PhD JDBC


JDBC Driver IX

Advantages

Dr.Poorna Chandra S PhD JDBC


JDBC Driver X

Better performance than all other drivers.


No software is required at client side or server side.
Disadvantages
Drivers depend on the Database.

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps I

There are 5 steps to connect any java application with the


database using JDBC.
These steps are as follows:

Register the Driver class


Create connection
Create statement
Execute queries
Close connectionn

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps II

Java Database Connectivity

1 Register the Driver class


The forName() method of Class class is used to register
the driver class. This method is used to dynamically load
the driver class.
Syntax of forName() method

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps III
1 public static void forName ( String className )
2 throws C l a s s N o t F o u n d E x c e p t i o n
3 Class . forName ( " oracle . jdbc . driver .
OracleDriver " ) ;

2 Create the connection object


The getConnection() method of DriverManager class is
used to establish connection with the database.
Syntax of getConnection() method
1 public static Connection getConnection ( String
url )
2 throws SQLException
3 public static Connection getConnection ( String
url , String name ,
4 String password )
5 throws SQLException
6

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps IV
7
8 Example :
9 Connection con = DriverManager . getConnection (
10 " jdbc : oracle : thin : @localhost :1521: xe " ," system
" ," password " ) ;

3 Create the Statement object


The createStatement() method of Connection interface is
used to create statement. The object of statement is
responsible to execute queries with the database.
Syntax of createStatement() method
1 public Statement createStatement () throws
SQLException
2
3 Example :
4 Statement stmt = con . createStatement () ;

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps V
4 Execute the query The executeQuery() method of
Statement interface is used to execute queries to the
database. This method returns the object of ResultSet
that can be used to get all the records of a table.
Syntac of executeQuery() method
1 public ResultSet executeQuery ( String sql )
throws SQLException
2
3
4 Example :
5 ResultSet rs = stmt . executeQuery ( " select * from
emp " ) ;
6

7 while ( rs . next () ) {
8 System . out . println ( rs . getInt (1) + " " + rs .
getString (2) ) ;
9 }

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with 5 steps VI

5 Close the connection object By closing connection


object statement and ResultSet will be closed
automatically. The close() method of Connection
interface is used to close the connection.
Syntax of close() method
1 public void close () throws SQLException
2
3 Example :
4 con . close () ;

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with Oracle I

To connect java application with the oracle database, we need


to follow 5 following steps. In this example, we are using
Oracle 10g as the database. So we need to know following
information for the oracle database:
1 Driver class:
The driver class for the oracle database is
oracle.jdbc.driver.OracleDriver
2 Connection URL:
The connection URL for the oracle10G database is
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

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with Oracle II
Oracle service name. You may get all these information
from the tnsnames.ora file.
3 Username:
The default username for the oracle database is system.
4 Password:
It is the password given by the user at the time of
installing the oracle database.

Create a Table
Before establishing connection, let’s first create a table in
oracle database. Following is the SQL query to create a table.
create table emp(id number(10),name varchar2(40),age
number(3));
Example

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with Oracle III
1 import java . sql .*;
2 class OracleCon {
3 public static void main ( String args []) {
4 try {
5 // step1 load the driver class
6 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
7
8 // step2 create the connection object
9 Connection con = DriverManager . getConnection (
10 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
11
12 // step3 create the statement object
13 Statement stmt = con . createStatement () ;
14
15 // step4 execute query

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with Oracle IV

16 ResultSet rs = stmt . executeQuery ( " select * from


emp " ) ;
17 while ( rs . next () )
18 System . out . println ( rs . getInt (1) + " " + rs .
getString (2) + " " + rs . getString (3) ) ;
19
20 // step5 close the connection object
21 con . close () ;
22
23 } catch ( Exception e ) { System . out . println ( e ) ;}
24
25 }
26 }

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with MySQL I

To connect Java application with the MySQL database, we


need to follow 5 following steps.
1 Driver class:
The driver class for the oracle database is
com.mysql.jdbc.Driver
2 Connection URL:
The connection URL for the oracle10G database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the
API, mysql is the database, localhost is the server name
on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name.
We may use any database, in such case, we need to
replace the sonoo with our database name.

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with MySQL II

3 Username:
The default username for the oracle database is root
4 Password:
It is the password given by the user at the time of
installing the mysql database. In this example, we are
going to use root as a password
Create a Table
Let’s first create a table in the mysql database, but before
creating table, we need to create database first.
create database sonoo; use sonoo; create table
emp(id int(10),name varchar(40),age int(3));
Example

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with MySQL III
1 import java . sql .*;
2 class MysqlCon {
3 public static void main ( String args []) {
4 try {
5 Class . forName ( " com . mysql . jdbc . Driver " ) ;
6 Connection con = DriverManager . getConnection (
7 " jdbc : mysql :// localhost :3306/ sonoo " ," root " ,"
root " ) ;
8 // here sonoo is database name , root is
username and password
9 Statement stmt = con . createStatement () ;
10 ResultSet rs = stmt . executeQuery ( " select * from
emp " ) ;
11 while ( rs . next () )
12 System . out . println ( rs . getInt (1) + " " + rs .
getString (2) + " " + rs . getString (3) ) ;
13 con . close () ;
14 } catch ( Exception e ) { System . out . println ( e ) ;}

Dr.Poorna Chandra S PhD JDBC


Java Database Connectivity with MySQL IV

15 }
16 }

Dr.Poorna Chandra S PhD JDBC


Drivermanager class I

The DriverManager class is the component of JDBC API and


also a member of the java.sql package. The DriverManager
class acts as an interface between users and drivers. It keeps
track of the drivers that are available and handles establishing
a connection between a database and the appropriate driver. It
contains all the appropriate methods to register and deregister
the database driver class and to create a connection between a
Java application and the database. The DriverManager class
maintains a list of Driver classes that have registered
themselves by calling the method
DriverManager.registerDriver(). Note that before interacting
with a Database, it is a mandatory process to register the
driver; otherwise, an exception is thrown.

Dr.Poorna Chandra S PhD JDBC


Drivermanager class II
Methods of the DriverManager class

Dr.Poorna Chandra S PhD JDBC


Drivermanager class III

Dr.Poorna Chandra S PhD JDBC


Connection interface I

A Connection is a session between a Java application and a


database. It helps to establish a connection with the database.
The Connection interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData, i.e., an 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(), setAutoCommit(), setTransactionIsolation(), etc.
Commonly used methods of Connection interface

1 public Statement createStatement():


creates a statement object that can be used to execute
SQL queries.

Dr.Poorna Chandra S PhD JDBC


Connection interface II
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 is 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.
Dr.Poorna Chandra S PhD JDBC
Statement Interface I
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
Commonly used methods of Statement interface:

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.
Dr.Poorna Chandra S PhD JDBC
Statement Interface II
4 public int[] executeBatch():
is used to execute batch of commands.
Example of Statement interface
1 import java . sql .*;
2 class FetchRecord {
3 public static void main ( String args []) throws
Exception {
4 Class . forName ( " oracle . jdbc . driver .
OracleDriver " ) ;
5 Connection con = DriverManager . getConnection ( "
jdbc : oracle : thin : @localhost :1521: xe " ,
6 " system " ," oracle " ) ;
7 Statement stmt = con . createStatement () ;
8
9 // stmt . executeUpdate (" insert into emp765
values (33 , ’ Irfan ’ ,50000) ") ;

Dr.Poorna Chandra S PhD JDBC


Statement Interface III

10 // int result = stmt . executeUpdate (" update


emp765 set name = ’ Vimal ’, salary =10000
where id =33") ;
11 int result = stmt . executeUpdate ( " delete from
emp765 where id =33 " ) ;
12 System . out . println ( result + " records affected "
);
13 con . close () ;
14 }}

Dr.Poorna Chandra S PhD JDBC


ResultSet interface I

The ResultSet interface provides getter methods ( getBoolean


, getLong , and so on) for retrieving column values from the
current row. Values can be retrieved using either the index
number of the column or the name of the column.

Dr.Poorna Chandra S PhD JDBC


ResultSet interface II
Commonly used methods of ResultSet interface:

Dr.Poorna Chandra S PhD JDBC


ResultSet interface III

Example of Scrollable ResultSet


1 import java . sql .*;
2 class FetchRecord {
3 public static void main ( String args []) throws
Exception {
4

5 Class . forName ( " oracle . jdbc . driver . OracleDriver " )


;
6 Connection con = DriverManager . getConnection ( " jdbc
: oracle : thin : @localhost :1521: xe " ,
7 " system " ," oracle " ) ;
8 Statement stmt = con . createStatement ( ResultSet .
TYPE_SCROLL_SENSITIVE ,

Dr.Poorna Chandra S PhD JDBC


ResultSet interface IV

9 ResultSet . CONCUR_UPDATABLE ) ;
10 ResultSet rs = stmt . executeQuery ( " select * from
emp765 " ) ;
11

12 // getting the record of 3 rd row


13 rs . absolute (3) ;
14 System . out . println ( rs . getString (1) + " " + rs .
getString (2) + " " + rs . getString (3) ) ;
15
16 con . close () ;
17 }}

Dr.Poorna Chandra S PhD JDBC


PreparedStatement interface I

A PreparedStatement is a pre-compiled SQL statement. It is a


subinterface of Statement. Prepared Statement objects have
some useful additional features than Statement objects.
Instead of hard coding queries, PreparedStatement object
provides a feature to execute a parameterized query.
Let’s see the example of parameterized query:
1 String sql = " insert into emp values (? ,? ,?) " ;

Why use PreparedStatement? Improves performance:


The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only
once.

Dr.Poorna Chandra S PhD JDBC


PreparedStatement interface II
Methods of PreparedStatement interface

Example of PreparedStatement interface that inserts


the record
Dr.Poorna Chandra S PhD JDBC
PreparedStatement interface III
1 First of all create table as given below:
1 create table emp ( id number (10) , name varchar2
(50) ) ;

1 import java . sql .*;


2 class InsertPrepared {
3 public static void main ( String args []) {
4 try {
5 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
6
7 Connection con = DriverManager . getConnection ( " jdbc
: oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
8
9 PreparedS tateme nt stmt = con . prepareStatement ( "
insert into Emp values (? ,?) " ) ;

Dr.Poorna Chandra S PhD JDBC


PreparedStatement interface IV

10 stmt . setInt (1 ,101) ; // 1 specifies the first


parameter in the query
11 stmt . setString (2 , " Ratan " ) ;
12
13 int i = stmt . executeUpdate () ;
14 System . out . println ( i + " records inserted " ) ;
15

16 con . close () ;
17
18 } catch ( Exception e ) { System . out . println ( e ) ;}
19
20 }
21 }

Dr.Poorna Chandra S PhD JDBC


ResultSetMetaData interface I

The metadata means data about data i.e. we can get further
information from the data.
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.
Commonly used methods of ResultSetMetaData
interface

Dr.Poorna Chandra S PhD JDBC


ResultSetMetaData interface II

How to get the object of ResultSetMetaData


1 public Re sultSe tMeta Data getMetaData () throws
SQLException

Examples of ResultSetMetaData interface:


Dr.Poorna Chandra S PhD JDBC
ResultSetMetaData interface III
1 import java . sql .*;
2 class Rsmd {
3 public static void main ( String args []) {
4 try {
5 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
6 Connection con = DriverManager . getConnection (
7 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
8
9 PreparedS tateme nt ps = con . prepareStatement ( "
select * from emp " ) ;
10 ResultSet rs = ps . executeQuery () ;
11 ResultSet MetaDa ta rsmd = rs . getMetaData () ;
12
13 System . out . println ( " Total columns : " + rsmd .
getColumnCount () ) ;

Dr.Poorna Chandra S PhD JDBC


ResultSetMetaData interface IV

14 System . out . println ( " Column Name of 1 st column : "


+ rsmd . getColumnName (1) ) ;
15 System . out . println ( " Column Type Name of 1 st
column : " + rsmd . ge tColu mnType Name (1) ) ;
16

17 con . close () ;
18 } catch ( Exception e ) { System . out . println ( e ) ;}
19 }
20 }

Dr.Poorna Chandra S PhD JDBC


DatabaseMetaData interface I

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 of DatabaseMetaData
interface

1 public String getDriverName()throws SQLException:


it returns the name of the JDBC driver.
2 public String getDriverVersion()throws SQLException:
it returns the version number of the JDBC driver.
3 public String getUserName()throws SQLException:
it returns the username of the database.

Dr.Poorna Chandra S PhD JDBC


DatabaseMetaData interface II

4 public String getDatabaseProductName()throws


SQLException:
it returns the product name of the database.
5 public String getDatabaseProductVersion()throws
SQLException:
it returns the product version of the database.
6 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.

Dr.Poorna Chandra S PhD JDBC


DatabaseMetaData interface III
How to get the object of DatabaseMetaData: The
getMetaData() method of Connection interface returns the
object of DatabaseMetaData. Syntax:
1 public DatabaseMetaData getMetaData () throws
SQLException

Simple Example of DatabaseMetaData interface :


1 import java . sql .*;
2 class Dbmd {
3 public static void main ( String args []) {
4 try {
5 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
6
7 Connection con = DriverManager . getConnection (
8 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;

Dr.Poorna Chandra S PhD JDBC


DatabaseMetaData interface IV
9 DatabaseMetaData dbmd = con . getMetaData () ;
10
11 System . out . println ( " Driver Name : " + dbmd .
getDriverName () ) ;
12 System . out . println ( " Driver Version : " + dbmd .
getDriverVersion () ) ;
13 System . out . println ( " UserName : " + dbmd . getUserName
() ) ;
14 System . out . println ( " Database Product Name : " +
dbmd . g e t D a t a b a s e P r o d u c t N a m e () ) ;
15 System . out . println ( " Database Product Version : " +
dbmd . g e t D a t a b a s e P r o d u c t V e r s i o n () ) ;
16
17 con . close () ;
18 } catch ( Exception e ) { System . out . println ( e ) ;}
19 }
20 }

Dr.Poorna Chandra S PhD JDBC


DatabaseMetaData interface V

Dr.Poorna Chandra S PhD JDBC


Storing image in Oracle I

You can store images in the database in java by the help of


PreparedStatement interface. The setBinaryStream()
method of PreparedStatement is used to set Binary
information into the parameterIndex.
Signature of setBinaryStream method The syntax of
setBinaryStream() method is given below:
1 public void setBinaryStream ( int paramIndex ,
InputStream stream )
2 throws SQLException
3 public void setBinaryStream ( int paramIndex ,
InputStream stream , long length )
4 throws SQLException

Dr.Poorna Chandra S PhD JDBC


Storing image in Oracle II
For storing image into the database, BLOB (Binary Large
Object) datatype is used in the table. For example:

Let’s write the jdbc code to store the image in the database.
Here we are using d:
d.jpg for the location of image. You can change it according
to the image location.
Example

Dr.Poorna Chandra S PhD JDBC


Storing image in Oracle III
1 import java . sql .*;
2 import java . io .*;
3 public class InsertImage {
4 public static void main ( String [] args ) {
5 try {
6 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
7 Connection con = DriverManager . getConnection (
8 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
9
10 PreparedS tateme nt ps = con . prepareStatement ( "
insert into imgtable values (? ,?) " ) ;
11 ps . setString (1 , " sonoo " ) ;
12
13 FileInputStream fin = new FileInputStream ( " d :\\ g .
jpg " ) ;
14 ps . setBinaryStream (2 , fin , fin . available () ) ;

Dr.Poorna Chandra S PhD JDBC


Storing image in Oracle IV

15 int i = ps . executeUpdate () ;
16 System . out . println ( i + " records affected " ) ;
17
18 con . close () ;
19 } catch ( Exception e ) { e . printStackTrace () ;}
20 }
21 }

Dr.Poorna Chandra S PhD JDBC


Retrieving image from Oracle I
By the help of PreparedStatement we can retrieve and store
the image in the database.
The getBlob() method of PreparedStatement is used to get
Binary information, it returns the instance of Blob. After
calling the getBytes()method on the blob object, we can get
the array of binary information that can be written into the
image file. Signature of getBlob() method of
PreparedStatement

Signature of getBytes() method of Blob interface

We are assuming that image is stored in the imgtable


Dr.Poorna Chandra S PhD JDBC
Retrieving image from Oracle II

Now let’s write the code to retrieve the image from the
database and write it into the directory so that it can be
displayed.
In AWT, it can be displayed by the Toolkit class. In servlet,
jsp, or html it can be displayed by the img tag. Example

Dr.Poorna Chandra S PhD JDBC


Retrieving image from Oracle III
1 import java . sql .*;
2 import java . io .*;
3 public class RetrieveImage {
4 public static void main ( String [] args ) {
5 try {
6 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
7 Connection con = DriverManager . getConnection (
8 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
9
10 PreparedS tateme nt ps = con . prepareStatement ( "
select * from imgtable " ) ;
11 ResultSet rs = ps . executeQuery () ;
12 if ( rs . next () ) { // now on 1 st row
13
14 Blob b = rs . getBlob (2) ; // 2 means 2 nd column data

Dr.Poorna Chandra S PhD JDBC


Retrieving image from Oracle IV
15 byte barr []= b . getBytes (1 ,( int ) b . length () ) ; // 1
means first image
16
17 FileOutputStream fout = new FileOutputStream ( " d :\\
sonoo . jpg " ) ;
18 fout . write ( barr ) ;
19
20 fout . close () ;
21 } // end of if
22 System . out . println ( " ok " ) ;
23
24 con . close () ;
25 } catch ( Exception e ) { e . printStackTrace () ; }
26 }
27 }

Dr.Poorna Chandra S PhD JDBC


Storing file in Oracle I

The setCharacterStream() method of PreparedStatement is


used to set character information into the parameterIndex.
Syntax

Dr.Poorna Chandra S PhD JDBC


Storing file in Oracle II

Java Example to store file in database


1 import java . io .*;
2 import java . sql .*;
3
4 public class StoreFile {
5 public static void main ( String [] args ) {
6 try {
7 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
8 Connection con = DriverManager . getConnection (

Dr.Poorna Chandra S PhD JDBC


Storing file in Oracle III
9 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
10
11 PreparedS tateme nt ps = con . prepareStatement (
12 " insert into filetable values (? ,?) " ) ;
13

14 File f = new File ( " d :\\ myfile . txt " ) ;


15 FileReader fr = new FileReader ( f ) ;
16
17 ps . setInt (1 ,101) ;
18 ps . set Ch ar ac te rS tr ea m (2 , fr ,( int ) f . length () ) ;
19 int i = ps . executeUpdate () ;
20 System . out . println ( i + " records affected " ) ;
21
22 con . close () ;
23
24 } catch ( Exception e ) { e . printStackTrace () ;}
25 }

Dr.Poorna Chandra S PhD JDBC


Storing file in Oracle IV

26 }

Dr.Poorna Chandra S PhD JDBC


Retrieving file from Oracle I
The getClob() method of PreparedStatement is used to get
file information from the database.
Syntax

Let’s
see the table structure of this example to retrieve the file.

Dr.Poorna Chandra S PhD JDBC


Retrieving file from Oracle II
Example to retrieve the file from the Oracle database is
given below
1 import java . io .*;
2 import java . sql .*;
3
4 public class RetrieveFile {
5 public static void main ( String [] args ) {
6 try {
7 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
8 Connection con = DriverManager . getConnection (
9 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
10
11 PreparedS tateme nt ps = con . prepareStatement ( "
select * from filetable " ) ;
12 ResultSet rs = ps . executeQuery () ;
13 rs . next () ; // now on 1 st row

Dr.Poorna Chandra S PhD JDBC


Retrieving file from Oracle III
14
15 Clob c = rs . getClob (2) ;
16 Reader r = c . ge tC har ac te rS tr ea m () ;
17
18 FileWriter fw = new FileWriter ( " d :\\ retrivefile .
txt " ) ;
19
20 int i ;
21 while (( i = r . read () ) != -1)
22 fw . write (( char ) i ) ;
23
24 fw . close () ;
25 con . close () ;
26

27 System . out . println ( " success " ) ;


28 } catch ( Exception e ) { e . printStackTrace () ; }
29 }
30 }

Dr.Poorna Chandra S PhD JDBC


CallableStatement I

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.

Dr.Poorna Chandra S PhD JDBC


CallableStatement II

Difference Between stored procedure and function

Dr.Poorna Chandra S PhD JDBC


CallableStatement III
How to get the instance of CallableStatement? The
prepareCall() method of Connection interface returns the
instance of CallableStatement. Syntax is given below:

The example to get the instance of CallableStatement


is given below:

Full example to call the stored procedure using JDBC


To call the stored procedure, you need to create it in the
database. Here, we are assuming that stored procedure looks
like this.

Dr.Poorna Chandra S PhD JDBC


CallableStatement IV

The table structure is given below:

In
this example we are going to call the stored procedure
INSERTR that receives id and name as the parameter and
inserts it into the table user420. Note that you need to create
the user420 table as well to run this application.
Dr.Poorna Chandra S PhD JDBC
CallableStatement V
1 import java . sql .*;
2 public class Proc {
3 public static void main ( String [] args ) throws
Exception {
4
5 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
6 Connection con = DriverManager . getConnection (
7 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
8
9 CallableS tateme nt stmt = con . prepareCall ( " { call
insertR (? ,?) } " ) ;
10 stmt . setInt (1 ,1011) ;
11 stmt . setString (2 , " Amit " ) ;
12 stmt . execute () ;
13
14 System . out . println ( " success " ) ;

Dr.Poorna Chandra S PhD JDBC


CallableStatement VI
15 }
16 }

Example to call the function using JDBC


In this example, we are calling the sum4 function that receives
two input and returns the sum of the given number. Here, we
have used the registerOutParameter method of
CallableStatement interface, that registers the output
parameter with its corresponding type. It provides information
to the CallableStatement about the type of result being
displayed.
The Types class defines many constants such as INTEGER,
VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc.

Dr.Poorna Chandra S PhD JDBC


CallableStatement VII

Let’s create the simple function in the database first.

Now, let’s write the simple program to call the function.

Dr.Poorna Chandra S PhD JDBC


CallableStatement VIII
1 import java . sql .*;
2
3 public class FuncSum {
4 public static void main ( String [] args ) throws
Exception {
5

6 Class . forName ( " oracle . jdbc . driver . OracleDriver " )


;
7 Connection con = DriverManager . getConnection (
8 " jdbc : oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
9

10 CallableS tateme nt stmt = con . prepareCall ( " {?= call


sum4 (? ,?) } " ) ;
11 stmt . setInt (2 ,10) ;
12 stmt . setInt (3 ,43) ;
13 stmt . r e g i s t e r O u t P a r a m e t e r (1 , Types . INTEGER ) ;
14 stmt . execute () ;

Dr.Poorna Chandra S PhD JDBC


CallableStatement IX

15
16 System . out . println ( stmt . getInt (1) ) ;
17
18 }
19 }

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC I

Transaction represents a single unit of work.


The ACID properties describes the transaction management
well. ACID stands for Atomicity, Consistency, isolation and
durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one
consistent state to another consistent state.
Isolationensures that transaction is isolated from other
transaction.
Durabilitymeans once a transaction has been committed, it
will remain so, even in the event of errors, power loss etc.
Advantages of Transaction Management fast
performanceIt makes the performance fast because database
is hit at the time of commit.

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC II

Simple example of transaction management in jdbc


using Statement
Dr.Poorna Chandra S PhD JDBC
Transaction Management using JDBC III
1 import java . sql .*;
2 class FetchRecords {
3 public static void main ( String args []) throws
Exception {
4 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
5 Connection con = DriverManager . getConnection ( " jdbc
: oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
6 con . setAutoCommit ( false ) ;
7
8 Statement stmt = con . createStatement () ;
9 stmt . executeUpdate ( " insert into user420 values
(190 , ’ abhi ’ ,40000) " ) ;
10 stmt . executeUpdate ( " insert into user420 values
(191 , ’ umesh ’ ,50000) " ) ;
11
12 con . commit () ;

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC IV
13 con . close () ;
14 }}

If you see the table emp400, you will see that 2 records has
been added.

Example of transaction management in jdbc using


PreparedStatement Let’s see the simple example of
transaction management using PreparedStatement.
1 import java . sql .*;
2 import java . io .*;
3 class TM {
4 public static void main ( String args []) {
5 try {
6

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC V
7 Class . forName ( " oracle . jdbc . driver . OracleDriver " )
;
8 Connection con = DriverManager . getConnection ( " jdbc
: oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
9 con . setAutoCommit ( false ) ;
10
11 PreparedS tateme nt ps = con . prepareStatement ( "
insert into user420 values (? ,? ,?) " ) ;
12
13 BufferedReader br = new BufferedReader ( new
Inpu tStre amRead er ( System . in ) ) ;
14 while ( true ) {
15
16 System . out . println ( " enter id " ) ;
17 String s1 = br . readLine () ;
18 int id = Integer . parseInt ( s1 ) ;
19

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC VI
20 System . out . println ( " enter name " ) ;
21 String name = br . readLine () ;
22
23 System . out . println ( " enter salary " ) ;
24 String s3 = br . readLine () ;
25 int salary = Integer . parseInt ( s3 ) ;
26
27 ps . setInt (1 , id ) ;
28 ps . setString (2 , name ) ;
29 ps . setInt (3 , salary ) ;
30 ps . executeUpdate () ;
31

32 System . out . println ( " commit / rollback " ) ;


33 String answer = br . readLine () ;
34 if ( answer . equals ( " commit " ) ) {
35 con . commit () ;
36 }
37 if ( answer . equals ( " rollback " ) ) {

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC VII
38 con . rollback () ;
39 }
40
41
42 System . out . println ( " Want to add more records y / n
");
43 String ans = br . readLine () ;
44 if ( ans . equals ( " n " ) ) {
45 break ;
46 }
47
48 }
49 con . commit () ;
50 System . out . println ( " record successfully saved " ) ;
51
52 con . close () ; // before closing connection commit ()
is called
53 } catch ( Exception e ) { System . out . println ( e ) ;}

Dr.Poorna Chandra S PhD JDBC


Transaction Management using JDBC VIII

54
55 }}

It will ask to add more records until you press n. If you press
n, transaction is committed.

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC I

Instead of executing a single query, we can execute a batch


(group) of queries. It makes the performance fast. It is
because when one sends multiple statements of SQL at once
to the database, the communication overhead is reduced
significantly, as one is not communicating with the database
frequently, which in turn results to fast performance.
The java.sql.Statement and java.sql.PreparedStatement
interfaces provide methods for batch processing.

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC II
Methods of Statement interface

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC III

Example of batch processing in JDBC Let’s see the simple


example of batch processing in JDBC. It follows following
steps:

1 Load the driver class


2 Create Connection
3 Create Statement
4 Add query in the batch
5 Execute Batch
6 Close Connection

Example of batch processing using PreparedStatement


Dr.Poorna Chandra S PhD JDBC
Batch Statement using JDBC IV
1 import java . sql .*;
2 import java . io .*;
3 class BP {
4 public static void main ( String args []) {
5 try {
6

7 Class . forName ( " oracle . jdbc . driver . OracleDriver " )


;
8 Connection con = DriverManager . getConnection ( " jdbc
: oracle : thin : @localhost :1521: xe " ," system " ,"
oracle " ) ;
9

10 PreparedS tateme nt ps = con . prepareStatement ( "


insert into user420 values (? ,? ,?) " ) ;
11
12 BufferedReader br = new BufferedReader ( new
Inpu tStre amRead er ( System . in ) ) ;
13 while ( true ) {

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC V
14
15 System . out . println ( " enter id " ) ;
16 String s1 = br . readLine () ;
17 int id = Integer . parseInt ( s1 ) ;
18
19 System . out . println ( " enter name " ) ;
20 String name = br . readLine () ;
21
22 System . out . println ( " enter salary " ) ;
23 String s3 = br . readLine () ;
24 int salary = Integer . parseInt ( s3 ) ;
25

26 ps . setInt (1 , id ) ;
27 ps . setString (2 , name ) ;
28 ps . setInt (3 , salary ) ;
29
30 ps . addBatch () ;

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC VI
31 System . out . println ( " Want to add more records y / n
");
32 String ans = br . readLine () ;
33 if ( ans . equals ( " n " ) ) {
34 break ;
35 }
36
37 }
38 ps . executeBatch () ; // for executing the batch
39
40 System . out . println ( " record successfully saved " ) ;
41

42 con . close () ;
43 } catch ( Exception e ) { System . out . println ( e ) ;}
44
45 }}

Dr.Poorna Chandra S PhD JDBC


Batch Statement using JDBC VII

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet I

An instance of RowSet is the Java bean component because it


has properties and Java bean notification mechanism. It is the
wrapper of ResultSet. A JDBC RowSet facilitates a
mechanism to keep the data in tabular form. It happens to
make the data more flexible as well as easier as compared to a
ResultSet. The connection between the data source and the
RowSet object is maintained throughout its life cycle. The
RowSet supports development models that are
component-based such as JavaBeans, with the standard set of
properties and the mechanism of event notification.
It was in the JDBC 2.0, the support for the RowSet was
introduced using the optional packages. But the
implementations were standardized for RowSet in the JDBC
RowSet Implementations Specification (JSR-114) by the Sun

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet II

Microsystems that is being present in the JDK (Java


Development Kit) 5.0.
The implementation classes of the RowSet interface are
as follows:

1 jdbcRowSet
2 CachedRowSet
3 WebRowSet
4 joinRowSet
5 FilteredRowSet

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet III

Example of JdbcRowSet Let’s see the simple example


of JdbcRowSet without event handling code.

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet IV
1 import java . sql . Connection ;
2 import java . sql . DriverManager ;
3 import java . sql . ResultSet ;
4 import java . sql . Statement ;
5 import javax . sql . RowSetEvent ;
6 import javax . sql . RowSetListener ;
7 import javax . sql . rowset . JdbcRowSet ;
8 import javax . sql . rowset . RowSetProvider ;
9
10 public class RowSetExample {
11 public static void main ( String [] args )
throws Exception {
12 Class . forName ( " oracle . jdbc .
driver . OracleDriver " ) ;
13
14 // Creating and Executing RowSet
15 JdbcRowSet rowSet = RowSetProvider .
newFactory () . createJdbcRowSet () ;

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet V
16 rowSet . setUrl ( " jdbc : oracle : thin :
@localhost :1521: xe " ) ;
17 rowSet . setUsername ( " system " ) ;
18 rowSet . setPassword ( " oracle " ) ;
19
20 rowSet . setCommand ( " select * from emp400 "
);
21 rowSet . execute () ;
22
23 while ( rowSet . next () ) {
24 // Generating cursor
Moved event
25 System . out . println ( " Id :
" + rowSet . getString (1) ) ;
26 System . out . println ( " Name
: " + rowSet . getString (2) ) ;
27 System . out . println ( "
Salary : " + rowSet . getString (3) ) ;

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet VI
28 }
29

30 }
31 }

Example of JDBC RowSet with Event Handling To


perform event handling with JdbcRowSet, you need to add the
Dr.Poorna Chandra S PhD JDBC
JDBC RowSet VII
instance of RowSetListener in the addRowSetListener method
of JdbcRowSet.
The RowSetListener interface provides 3 method that must be
implemented. They are as follows:

1 public void cursorMoved(RowSetEvent event);


2 public void rowChanged(RowSetEvent event);
3 public void rowSetChanged(RowSetEvent event);

Let’s write the code to retrieve the data and perform some
additional tasks while the cursor is moved, the cursor is
changed, or the rowset is changed. The event handling
operation can’t be performed using ResultSet, so it is preferred
now.

Example
Dr.Poorna Chandra S PhD JDBC
JDBC RowSet VIII
1 import java . sql . Connection ;
2 import java . sql . DriverManager ;
3 import java . sql . ResultSet ;
4 import java . sql . Statement ;
5 import javax . sql . RowSetEvent ;
6 import javax . sql . RowSetListener ;
7 import javax . sql . rowset . JdbcRowSet ;
8 import javax . sql . rowset . RowSetProvider ;
9
10 public class RowSetExample {
11 public static void main ( String [] args )
throws Exception {
12 Class . forName ( " oracle . jdbc .
driver . OracleDriver " ) ;
13
14 // Creating and Executing RowSet
15 JdbcRowSet rowSet = RowSetProvider .
newFactory () . createJdbcRowSet () ;

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet IX
16 rowSet . setUrl ( " jdbc : oracle : thin : @localhost
:1521: xe " ) ;
17 rowSet . setUsername ( " system " ) ;
18 rowSet . setPassword ( " oracle " ) ;
19
20 rowSet . setCommand ( " select * from emp400 "
);
21 rowSet . execute () ;
22
23 // Adding Listener and moving RowSet
24 rowSet . ad dRowSe tList ener ( new MyListener () ) ;
25

26 while ( rowSet . next () ) {


27 // Generating cursor
Moved event
28 System . out . println ( " Id :
" + rowSet . getString (1) ) ;

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet X
29 System . out . println ( " Name
: " + rowSet . getString (2) ) ;
30 System . out . println ( "
Salary : " + rowSet . getString (3) ) ;
31 }
32

33 }
34 }
35
36 class MyListener implements RowSetListener {
37 public void cursorMoved ( RowSetEvent event )
{
38 System . out . println ( " Cursor Moved
... " ) ;
39 }
40 public void rowChanged ( RowSetEvent event ) {
41 System . out . println ( " Cursor
Changed ... " ) ;

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet XI

42 }
43 public void rowSetChanged ( RowSetEvent event
) {
44 System . out . println ( " RowSet
changed ... " ) ;
45 }
46 }

Dr.Poorna Chandra S PhD JDBC


JDBC RowSet XII

Dr.Poorna Chandra S PhD JDBC

You might also like