0% found this document useful (0 votes)
28 views32 pages

JDBC Ii

Uploaded by

thirosul
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)
28 views32 pages

JDBC Ii

Uploaded by

thirosul
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/ 32

Unit - III

Working with Databases

 What is JDBC :-
 JDBC stands for Java Database Connectivity.
 Java Data Base Connectivity (JDBC) is a set of Java APIs used for
executing SQL statements. JDBC is much similar to Microsoft's Open
Database Connectivity (ODBC) interface to SQL (Structure Query
Language).
 JDBC API is a set of interfaces and classes to be used for communicating
with a data base.
 These interfaces and classes are found in the java.sql package.
 JDBC or Java Database Connectivity is a Java API to connect and execute
the query with the database.
 It is a specification from Sun microsystems that provides a standard
abstraction (API or Protocol) for java applications to communicate with
various databases.
 JDBC is an API(Application programming interface) used in java
programming to interact with databases.
 The classes and interfaces of JDBC allow the application to
send requests made by users to the specified database.
 The JDBC API consists of a set of interfaces and classes written in the Java
programming language.
 Using these standard interfaces and classes, programmers can write
applications that connect to databases, send queries written in structured
query language (SQL), and process the results.

 Steps to connect to the database in java :-


There are 7 steps to connect any java application with the database in java using
JDBC. They are as follows:
1. Importing packages.
2. Load and Register the driver class.
3. Creating connection.

Page 1 Prof. Patil R.M


.
4. Creating statement.
5. Creating Resultset
6. Processing Resultset
7. Closing connection.

1) Importing Packages
All the JDBC API classes and interfaces are stored in the package java.sql so it
is needed to import as-
import java.sql.*;

2) Load / 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.
Example to register the OracleDriver class-
Class.forName("oracle.jdbc.driver.OracleDriver");

Example to register the MySQL Driver class-


Class.forName("com.mysql.jdbc.Driver")

3) Create the connection object


The getConnection() method of DriverManager class is used to establish
connection with the database.
Example to establish connection with the Oracle database-
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","root","siit");
Example to establish connection with the MySQL database-
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/da
tabase","root","password");

4) 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.
Example to create the statement object-
Statement stmt=con.createStatement();

Page 2 Prof. Patil R.M


.
5) 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.
Example to execute query-
ResultSet rs = stmt.executeQuery("select * from employee");

6) Processing Resultset-
The records returned by the resultSet object has been processed /navigating by
using different methods as-
while(rs.next())
{
System.out.pritln(rs.getInt(1) + " " + rs.getString(2));
}

7) Close 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.
Example to close connection-
con.Close();

 JDBC Drivers / Types of Drivers:-


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

Type 1 and type 2 rely heavily on additional software, (typically C/C++ DLLs)
installed on the client computer to provide database connectivity.
Type 3 and 4 are pure java implementations and require no additional software
to be installed on the client, except for the JDBC driver.

Page 3 Prof. Patil R.M


.
Types of JDBC Driver

1) Type 1 Driver : JDBC-ODBC Bridge :-


 This drivers act as a "bridge" between JDBC and another database connectivity
mechanism such as ODBC.
 The JDBC- ODBC bridge provides JDBC access using most standard ODBC
drivers.
 In this driver the java statements are converted to JDBC statements.
 JDBC statements call the ODBC by using the JDBC-ODBC Bridge and finally
the query is executed by the database.
 This driver has serious limitation for many applications.
 This JDBC/ODBC Bridge does not support JDBC2.
 This bridge is helpful for testing but it cannot recommend for the production
used.
 Type-1 driver isn‟t written in java, that‟s why it isn‟t a portable driver.
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.

Page 4 Prof. Patil R.M


.
Advantages:
1. It can be used with any database for which an ODBC driver is installed.

Disadvantages:
1. Performance is not good as it converts JDBC method calls into ODBC function
calls.
2. ODBC driver needs to be installed on the client machine.
3. Platform dependent.

2) Type 2 Driver : Native API Driver :-


 The Native API driver uses the client -side libraries of the database.
 This driver converts JDBC method calls into native calls of the database API.
 In order to interact with different database, this driver needs their local API,
that‟s why data transfer is much more secure as compared to type-1 driver.
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn‟t written in java, that‟s why it isn‟t a portable driver
 It is a database dependent driver.

Advantages:
1. It is faster than a JDBC-ODBC bridge driver.

Disadvantages:
1. Platform dependent.
2. The vendor client library needs to be installed on the client machine.

Page 5 Prof. Patil R.M


.
3) Type 3 Driver: Network Protocol driver, Pure Java Driver:-
 The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol.
 Here all the database connectivity drivers are present in a single server, hence
no need of individual client-side installation.
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.
 Switch facility to switch over from one database to another database.

Advantages:
1. Platform independent.
2. Faster from Type1 and Type2 drivers.
3. It follows a three tier communication approach.
4. Multiple types of databases can be accessed at the same time.
Disadvantages:
1. It requires database-specific coding to be done in the middle tier.

Page 6 Prof. Patil R.M


.
4) Type 4 Driver: Native Protocol/ Pure Java Driver/ Thin Driver:-
 Type-4 driver is also called native protocol driver.
 This driver interact directly with database.
 It does not require any native database library, that is why it is also known as
Thin Driver.
 Does not require any native library and Middleware server, so no client-side or
server-side installation.
 It is fully written in Java language, hence they are portable drivers.

Advantages:
1. Platform independent.
2. Faster than all other drivers.
3. They are completely written in java to achieve platform independence and
eliminate deployment administration issues.

Disadvantages:
1. It is database dependent.
2. Multiple types of databases can‟t be accessed at the same time.

Page 7 Prof. Patil R.M


.
 JDBC - Exceptions Handling :-
 Exception handling allows you to handle exceptional conditions such as
program-defined errors in a controlled fashion.
 When an exception condition occurs, an exception is thrown.
 The term thrown means that current program execution stops, and control is
redirected to the nearest applicable catch clause.
 If no applicable catch clause exists, then the program's execution ends.
 JDBC Exception handling is very similar to Java Excpetion handling but for
JDBC, the most common exception you'll deal with is java.sql.SQLException.
 SQLException Methods: A SQLException can occur both in the driver and
the database. When such an exception occurs, an object of type SQLException
will be passed to the catch clause.

Method Description

Gets the error number associated with the


getErrorCode( )
exception.

Gets the JDBC driver's error message for an


getMessage( ) error handled by the driver or gets the Oracle
error number and message for a database error.

Gets the XOPEN SQLstate string. For a JDBC


driver error, no useful information is returned
getSQLState( ) from this method. For a database error, the
five-digit XOPEN SQLstate code is returned.
This method can return null.

Gets the next Exception object in the


getNextException( )
exception chain.

Prints the current exception, or throwable, and


printStackTrace( )
its backtrace to a standard error stream.

Prints this throwable and its backtrace to the


printStackTrace(PrintStream s)
print stream you specify.

Prints this throwable and its backtrace to the


printStackTrace(PrintWriter w)
print writer you specify.

Page 8 Prof. Patil R.M


.
By utilizing the information available from the Exception object, you can catch an
exception and continue your program appropriately. Here is the general form of a try
block:

try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}

Example:
Study the following example code to understand the usage of try.... catch...
finally blocks.

//STEP 1. Import required packages


import java.sql.*;

public class JDBCExample {


public static void main(String[] args)
{ Connection conn = null;
try{

//STEP 2: Register JDBC driver


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

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn =
DriverManager.getConnection(“Jdbc:Oracle:thin:@localhost:1521:
XE”,”system”,”siit”);

//STEP 4: Execute a query


System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT rollno, name, mobile FROM student";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int rollno = rs.getInt("rollno");
String name = rs.getString("name");

Page 9 Prof. Patil R.M


.
int mobile = rs.getInt("mobile");

//Display values
System.out.print("Roll No: " + rollno);
System.out.print(", Name: " + name);
System.out.print(", Mobile: " + mob);
}

//STEP 6: Clean-up environment


rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException
se){ se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

 Major Classes and Interfaces of JDBC:-


Java provides various interfaces and classes for connecting to the databases and
executing SQL statements. Following are the classes and interfaces allow us to load
the database driver, establishing a connection and fire the query.

1) DriverManager class :-
 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.

Page 10 Prof. Patil R.M


.
 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.

Methods of the DriverManager Class :-


1) public static void registerDriver(Driver driver): This method is used to
register the given driver with DriverManager. No action is performed by the
method when the given driver is already registered.

2) Public static void deregisterDriver(Driver driver): This method is used to


deregister the given driver (drop the driver from the list) with DriverManager.
If the given driver has been removed from the list, then no action is performed
by the method.

3) public static Connection getConnection(String url) : This method is used to


establish the connection with the specified url. The SQLException is thrown
when the corresponding Driver class of the given database is not registered
with the DriverManager.

4) public static Connection getConnection(String url, String userName,


String password) : This method is used to establish the connection with the
specified url, username, and password. The SQLException is thrown when the
corresponding Driver class of the given database is not registered with the
DriverManager.

5) public static Driver getDriver(String url) : Those drivers that understand the
mentioned URL (present in the parameter of the method) are returned by this
method provided those drivers are mentioned in the list of registered drivers.
Program :-
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println(“Connection to database created…”);


con.close();
}
}

Page 11 Prof. Patil R.M


.
2) Connection Interface :-
 A connection is a session between java application and database.
 It helps to establish a connection with the database.
 The JDBC connection interface provides methods to handle transaction
processing, create object for executing SQL statement.
 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.

Commonly used methods of Connection interface:


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

7) PreparedStatement preaparedStatemet(String sql) :


The preparedStatement object is used to execute dynamic SQL statements
against the database. A dynamic SQL statement is a statement in which some
of the parameters (values) in the statement are unknown when the statement is
created.

Connection Interface Fields :-


There are some common Connection interface constant fields that are present
in the Connect interface. These fields specify the isolation level of a transaction.

Page 12 Prof. Patil R.M


.
1) TRANSACTION_NONE: No transaction is supported, and it is indicated by
this constant.
2) TRANSACTION_READ_COMMITTED: It is a constant which shows that
the dirty reads are not allowed. However, phantom reads and non-repeatable
reads can occur.
3) TRANSACTION_READ_UNCOMMITTED: It is a constant which shows
that dirty reads, non-repeatable reads, and phantom reads can occur.
4) TRANSACTION_REPEATABLE_READ: It is a constant which shows that
the non-repeatable reads and dirty reads are not allowed. However, phantom
reads and can occur.
5) TRANSACTION_SERIALIZABLE: It is a constant which shows that the
non-repeatable reads, dirty reads as well as the phantom reads are not allowed.

Program :-
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println(“Connection to database created…”);


Statement sta = con.createStatement();
System.out.println(“Statement Object created…”);

con.close();
}
}

3) Statement interface :-
 The Statement interface provides methods to execute queries with the database.
 The statement interface is used to create SQL basic statements in Java it provides
methods to execute queries with the database.
 The object of this interface is used for firing a static SQL or PL/SQL queries and
returning the results it has produced.
 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:


The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It

Page 13 Prof. Patil R.M


.
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. Returns the number of rows affected by the
execution of the SQL statement.
3) public boolean execute(String sql): Returns a boolean value of true if a ResultSet
object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL
statements or when you need to use truly dynamic SQL.
4) public int[] executeBatch(): is used to execute batch of commands.

Program :- Retrieving Records from table.

import java.sql.*;

public class abc {

public static void main(String[] args) throws


ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println("Connection to database created…");


Statement sta = con.createStatement();
System.out.println("Statement Object created…");
ResultSet r = sta.executeQuery("select * from student");

while (r.next())
{
System.out.println(r.getInt(1) + " " + r.getString(2));
}

con.close();
}

4) ResultSet interface:-

 A ResultSet provides access to a table of data. The java.sql.ResultSet interface


represents the result set of a database query.
 A ResultSet object maintains a cursor that points to the current row in the result set.
 The term “result set” refers to the row and column data contailned in a ResultSet
object.

Page 14 Prof. Patil R.M


.
 A ResultSet object is usually generated by executing a Statement. The ResultSet
object is actually a tabular data set; that is, it consists of rows of data organized in
uniform columns.
 In JDBC, the Java program can see only one row of data at one time. The program
uses the next() method to go to the next row.
 A ResultSet maintains a cursor pointing to its current row of data. Initially the cursor
is positioned
 The 'next' method moves the cursor to the next row. So in this program we are using
while (rs.next()).
 The method rs.next() returns a Boolean value depending on the record set. If it
reaches last record, false is returned and loop lapses.
 For maximum portability, ResultSet columns within each row should be read in left-
to-right order and each column should be read only once.
 We use getxxx() method of appropriate type to retrieve the value in each column.

Methods of ResultSet Interface:-

1) boolean next():- It is used to move the cursor to the one row next from the current
position.

2) boolean previous():- It is used to move the cursor to the one row previous from the
current position.

3) boolean first():- It is used to move the cursor to the first row in in the result set
object.

4) boolean last():- It is used to move the cursor to the last row in result set object.

5) boolean absolute (int row):- It is used to move the cursor to the specified row
number in the ResultSet object.

6) boolean relative (int row):- It is used to move the cursor to the relative row number
in the ResultSet object, it may be positive or negative.

7) int getInt (int columnIndex):- It is used to return the data of specified column index
of the current row as int.

8) int getInt (String columnName):- It is used to return the data of specified column
name of the current row as int.

9) String getString(int columnIndex):- It is used to return the data of specified column


index of the current row as String.

10) String getString (String columnName):- It is used to return the data of specified
column of the current row as String.

Page 15 Prof. Patil R.M


.
Program:-

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class abc {

public static void main(String[] args) throws


ClassNotFoundException, SQLException {
// TODO Auto-generated method stub

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println("Connection to database created...");


Statement sta =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT
ABLE);

ResultSet r = sta.executeQuery("select * from student");

//getting the record of 2nd row


r.absolute(2);

System.out.println(r.getInt(1) + " " + r.getString(2));

con.close();
}
}

5) PreparedStatement interface :-
 The PreparedStatement interface is a subinterface of Statement.
 A PreparedStatement is a pre-compiled SQL statement.
 It is used to execute parameterized query. The PreparedStatement interface
accepts input parameters at runtime.
 Let's see the example of parameterized query.
String sql = "insert into emp values(?,?,?)";
 We are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
 This interface is used when we plan to use the same SQL statement many time.

Page 16 Prof. Patil R.M


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

How to get the instance of PreparedStatement?


The prepareStatement() method of Connection interface is used to return the
object of PreparedStatement. Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException

Advantages of PreparedStatement
1) When PreparedStatement is created, the SQL query is passed as a parameter.
This Prepared Statement contains a pre-compiled SQL query, so when the
PreparedStatement is executed, DBMS can just run the query instead of first
compiling it.
2) We can use the same PreparedStatement and supply with different parameters
at the time of execution.
3) An important advantage of PreparedStatements is that they prevent SQL
injection attacks.

Methods of PreparedStatement interface


The important methods of PreparedStatement interface are given below:
1) setInt(int, int): This method can be used to set integer value at the given
parameter index.
2) setString(int, string): This method can be used to set string value at the
given parameter index.
3) setFloat(int, float): This method can be used to set float value at the given
parameter index.
4) setDouble(int, double): This method can be used to set a double value at the
given parameter index.
5) executeUpdate(): This method can be used to create, drop, insert, update,
delete etc. It returns int type.
6) executeQuery(): It returns an instance of ResultSet when a select query is
executed.

Program :- Inserting Record to student table using PreparedStatement Interface.


import java.sql.*;
import java.util.Scanner;

public class abc {

Page 17 Prof. Patil R.M


.
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println("Connection to database created…");


PreparedStatement ps = con.prepareStatement("insert into student
values(?, ?, ?)");

try (Scanner s1 = new Scanner(System.in))


{ System.out.println("Enter Roll Number");
int roll = s1.nextInt();
ps.setInt(1, roll);

System.out.println("Enter Name");
String name = s1.next();
ps.setString(2, name);

System.out.println("Enter Mobile Number");


long mobile = s1.nextLong();
ps.setLong(3, mobile);
}
int result = ps.executeUpdate();

System.out.println(result + "Records Inserted...");

con.close();
}
}

Program :- Deleting Record from student table using PreparedStatement Interface.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class abc {

public static void main(String[] args) throws SQLException {


// TODO Auto-generated method stub
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println("Connection to database created…");


PreparedStatement ps = con.prepareStatement("delete from student
where rollno = ?");

try (Scanner s1 = new Scanner(System.in))


{ System.out.println("Enter Roll Number which you want to
delete..");
int roll = s1.nextInt();
ps.setInt(1, roll);

Page 18 Prof. Patil R.M


.
}
int result = ps.executeUpdate();

System.out.println(result + "Records Deleted...");

con.close();
}
}

Program :- Updating Record in student table using PreparedStatement Interface.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class abc {

public static void main(String[] args) throws SQLException {


// TODO Auto-generated method stub
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");

System.out.println("Connection to database created…");


PreparedStatement ps = con.prepareStatement("update student set name
= ? where rollno = ?");

try (Scanner s1 = new Scanner(System.in))


{ System.out.println("Enter Roll Number which you want to
Update..");
int roll = s1.nextInt();
ps.setInt(2, roll);

System.out.println("Enter New Name");


String name = s1.next();
ps.setString(1, name);

}
int result = ps.executeUpdate();

System.out.println(result + "Records Updated...");

con.close();
}

6) CallableStatement Interface :-
 To call the stored procedures and functions, CallableStatement interface is
used.

Page 19 Prof. Patil R.M


.
 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 to 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.
 Following are the steps to use Callable Statement in Java to call Stored
Procedure:
1) Load MySQL driver and Create a database connection:-

import java.sql.*;

public class JavaApplication1 {


public static void main(String[] args) throws Exception
{
Class.forName(“com.mysql.jdbc.Driver”);
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "siit",
"Paniv");
}
}

2) Create a SQL String


We need to store the SQL query in a String.
String sql1 = ”insert into student values (?, ?, ?)”;

3) Create CallableStatement Object


The prepareCall() method of connection interface will be used to create
CallableStatement object. The sql_string will be passed as an argument to the
prepareCall() method.
CallableStatement cs = con.prepareCall(sql1);

4) Set the Input Parameters


Depending upon the data type of query parameters we can set the input parameter by
calling setInt() or setString() methods.
cs.setInt(1, 6);
cs.setString(2, ”Rahul”);
cs.setLong(3, 9850505050);

5) Call Stored Procedure


Execute stored procedure by calling execute() method of CallableStatement class.
Example of using Callable Statement in Java to call Stored Procedure

Page 20 Prof. Patil R.M


.
cs.execute();

Example : - 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.

create or replace procedure "INSERTR"


(id IN NUMBER,name IN VARCHAR2, mob IN NUMBER)
is
begin
insert into student values(id,name, mob);
end;
/

The table structure is given below:


create table student(rollno int, name varchar2(200)mobile
int);

In this example, we are going to call the stored procedure INSERTR that receives
rollno, name and mob as the parameter and inserts it into the table student. Note that
you need to create the student table as well to run this application.

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:@local
host:1521:xe","system","siit"); CallableStatement
stmt=con.prepareCall("{call insertR(?,?
, ?)}");
stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.setLong(3,9898989898);

stmt.execute();

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

Now check the table in the database, value is inserted in the student table.

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

Page 21 Prof. Patil R.M


.
of CallableStatement interface, that registers the output parameter with its

Page 22 Prof. Patil R.M


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

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

create or replace function sum4


(n1 in number,n2 in number)
return number
is
temp number(8);
begin
temp :=n1+n2;
return temp;
end;
/

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

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

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

}
}
Output: 53

Page 23 Prof. Patil R.M


.
 Example to connect to the Oracle database :-
For connecting java application with the oracle database, you need to follow 5 steps to
perform database connectivity. In this example we are using Oracle10g 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 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: Password is given by the user at the time of installing the oracle
database.
Let's first create a table in oracle
database.
create table emp(id number(10),name varchar2(40),age
number(3));

Example to Connect Java Application with Oracle database-


In this example, system is the username and „siit‟ is the password of the Oracle 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","siit");
//step3 create the statement object
Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from student");

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

Page 24 Prof. Patil R.M


.
System.out.println(e);
}
}
}

The above example will fetch all the records of student table.
To connect java application with the Oracle database ojdbc14.jar file is required to be loaded.
Two ways to load the jar file:
1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath
1) paste the ojdbc14.jar file in JRE/lib/ext folder:
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
 temporary
 permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;

How to set the permanent classpath:


Go to environment variable then click on new tab. In variable name
write classpath and in variable value paste the path to ojdbc14.jar by appending
ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdb
c14.jar;.;

 Example to connect to the mysql database


For connecting java application with the mysql database, you need to follow 5 steps to
perform database connectivity.
In this example we are using MySql as the database. So we need to know following
information for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/Database_name 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, you need to replace the Database_name with your database
name.
3. Username: The default username for the mysql database is root.

Page 25 Prof. Patil R.M


.
4. Password: Password is given by the user at the time of installing the mysql database.
In this example, we are going to use „siit‟ as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.

create database mydb;


use mydb;
create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database

In this example, mydb is the database name, root is the username and password is „siit‟.
import java.sql.*;
class MysqlCon
{
public static void main(String args[])
{
try{ Class.forName("com.mysql.jdbc.Driver
");
Connection con=DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/mydb","root","siit");
//here mydb is database name, root is username and passwor
d is „siit‟
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)
+" "+rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
The above example will fetch all the records of emp table.
To connect java application with the mysql database mysqlconnector.jar file is required to be
loaded.
Two ways to load the jar file:
1. paste the mysqlconnector.jar file in jre/lib/ext folder
2. set classpath
1) paste the mysqlconnector.jar file in JRE/lib/ext folder:
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
 temporary
 permament

Page 26 Prof. Patil R.M


.
How to set the temporary classpath
open command prompt and write:
C:>set classpath=c:\folder\mysql-connector-java-5.0.8-
bin.jar;.;

How to set the permanent classpath


Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending
mysqlconnector.jar;.; as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

 Connectivity with Access without DSN


There are two ways to connect java application with the access database.
1. Without DSN (Data Source Name)
2. With DSN
Java is mostly used with Oracle, mysql, or DB2 database. So you can learn this topic only for
knowledge.

Example to Connect Java Application with access without DSN

In this example, we are going to connect the java program with the access database. In such
case, we have created the login table in the access database. There is only one column in the
table named name. Let's get all the name of the login table.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";
//Here database exists in the current directory

String url="jdbc:odbc:Driver={Microsoft Access Driver


(*.mdb)};
DBQ=" + database + ";DriverID=22;READ
ONLY=true";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){ System.out.println(
rs.getString(1));
}

Page 27 Prof. Patil R.M


.
}catch(Exception ee){System.out.println(ee);}

}}

Example to Connect Java Application with access with DSN


Connectivity with type1 driver is not considered good. To connect java application with
type1 driver, create DSN first, here we are assuming your dsn name is mydsn.
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){ System.out.println(
rs.getString(1));
}

}catch(Exception ee){System.out.println(ee);}

}
}

Page 28 Prof. Patil R.M


.
 Example to store image in Oracle database:-
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)
throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length) thro
ws SQLException
For storing image into the database, BLOB (Binary Large Object) datatype is used in the
table. For example:

CREATE TABLE "IMGTABLE"("NAME" VARCHAR2(4000),"PHOTO" BLO


B)

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.

import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er"); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","siit");

PreparedStatement ps=con.prepareStatement("insert into im


gtable values(?,?)");
ps.setString(1,"sonoo");

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();}
}
}
If you see the table, record is stored in the database but image will not be shown. To do so,
you need to retrieve the image from the database.

Example to retrieve image from Oracle database


By the help of PreparedStatement we can retrieve and store the image in the database.

Page 29 Prof. Patil R.M


.
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


public Blob getBlob()throws SQLException
Signature of getBytes() method of Blob interface
public byte[] getBytes(long pos, int length)throws S
QLException
We are assuming that image is stored in the imgtable.

CREATE TABLE "IMGTABLE" ( "NAME" VARCHAR2(4000), "PHOTO" BLOB


)

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.

import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDriv
er"); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","siit");

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:\\myimage.j


pg");
fout.write(barr);

fout.close();
}//end of if
System.out.println("ok");

con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}

Page 30 Prof. Patil R.M


.
Now if you see the d drive, myimage.jpg image is created.

 Example to store file in Oracle database:


The setCharacterStream() method of PreparedStatement is used to set character
information into the parameterIndex.
Syntax:
public void setBinaryStream(int paramIndex,InputStream
stream)throws
SQLException

For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
CREATE TABLE "FILETABLE" ( "ID" NUMBER, "NAME" CLOB )
import java.io.*;
import java.sql.*;

public class StoreFile {


public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDrive
r");
Connection con=DriverManager.getConnection("jdbc:oracle:th
in:@localhost:1521:xe","system","siit");
PreparedStatement ps=con.prepareStatement("insert into fil
etable 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();}
}}

 Example to retrieve file from Oracle database:


The getClob() method of PreparedStatement is used to get file information from the database.
Syntax of getClob method
public Clob getClob(int columnIndex){}
Let's see the table structure of this example to retrieve the file.
CREATE TABLE "FILETABLE" ( "ID" NUMBER, "NAME" CLOB )

Page 31 Prof. Patil R.M


.
The example to retrieve the file from the Oracle database
is given below.
import java.io.*;
import java.sql.*;
public class RetrieveFile {
public static void main(String[] args) {
try{ Class.forName("oracle.jdbc.driver.OracleDrive
r"); Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","siit");

PreparedStatement ps=con.prepareStatement("select * from f


iletable");
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 32 Prof. Patil R.M


.

You might also like