You are on page 1of 65

Java JDBC

Java JDBC

• Java JDBC is a java API to connect and execute query


with the database.
• JDBC API uses jdbc drivers to connect with the
database.
Why use JDBC

• 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).
JDBC Architecture
Common JDBC Components

• DriverManager: This class manages a list of database drivers.


• Driver: This interface handles the communications with the
database server.
• Connection: This interface with all methods for contacting a
database
• Statement: You use objects created from this interface to
submit the SQL statements to the database
• ResultSet: These objects hold data retrieved from a database
after you execute an SQL query using Statement objects.
• SQLException: This class handles any errors that occur in a
database application.
JDBC Driver

• JDBC Driver is a software component that enables


java application to interact with the database.
• There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
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.
JDBC-ODBC bridge driver
JDBC-ODBC bridge driver

• Advantages:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method
call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the
client machine.
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.
Native-API driver
Native-API driver

• Advantage:
• performance upgraded than JDBC-ODBC
bridge driver.
• Disadvantage:
• The Native driver needs to be installed on the
each client machine.
• The Vendor client library needs to be installed
on client machine.
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.
Network Protocol driver
Network Protocol driver

• Advantage:
• No client side library is required because of application server
that can perform many tasks like auditing, load balancing,
logging etc.
• 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.
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.
Thin driver
Thin driver

• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server
side.
• Disadvantage:
• Drivers depends on the Database.
5 STEPS TO CONNECT TO THE
DATABASE IN JAVA
5 Steps to connect to the database
in java
• There are 5 steps to connect any java application
with the database in java using JDBC.
• They are as follows:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
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
Class.forName(drivername)
public static void forName(String
className)throws ClassNotFoundException
Driver Names
Create the connection object

• The getConnection() method of DriverManager class


is used to establish connection with the database.
public static Connection getConnection(String
url)throws SQLException
public static Connection getConnection(String
url,String name,String password)throws SQLException
con=DriverManager.getConnection(databaseUrl);
con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","pass
word");
Few Database URLs
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
public Statement createStatement()throws
SQLException
• Example to create the statement object
• Statement stmt=con.createStatement();
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.
• Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws
SQLException
Execute the query

• Example to execute query

ResultSet rs=stmt.executeQuery("select * from


emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
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
public void close()throws SQLException
• Example to close connection
con.close()
Create Statement
• The connection is used to send SQL statements to the
database.
• three interfaces are used for sending SQL statements to
databases
– Statement and its two sub-interfaces,
– PreparedStatement and Callable Statement.
• Three methods of the Connection object are used to return
objects of these three statements.
• A Statement object is used to send a simple SQL statement to
the database with no parameters.
– Statement stmt = con.createStatement();
Create Statement (contd.)
• A PreparedStatement object sends precompiled statements to
the databases with or without IN parameters.
• If n rows need to be inserted, then the same statement gets
compiled n number of times.
• So to increase efficiency, we use precompiled
PreparedStatement.
• only the values that have to be inserted are sent to the
database again and again.
– PreparedStatement ps = con.prepareStatement(String query);
• A CallableStatement object is used to call stored procedures.
– CallableStatement cs = con.prepareCall(String query);
Prepared Statement
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);

• Sent o database , prepared for execution


• The value of IN (?) parameters needs to be sent
• the ? symbol, which is known as the parameter marker

pstmt.setInt(1, 24);
pstmt.setString(2,”IT101”);
Execute Query
Execute Query
• Three methods are used
– ResultSet executeQuery(String sqlQuery) throws SQLException
– int executeUpdate(String sqlQuery) throws SQLException
– boolean execute(String sqlQuery) throws SQLException
• executeQuery is used for executing SQL statements that
return a single ResultSet, e.g. a select statement.
– The rows fetched from database are returned as a single ResultSet
object. For example,
– ResultSet rs=stmt.executeQuery(“select * from emp”);
• executeUpdate is used for DDL and DML SQL statements like
insert,update, delete, and create.
– returns an integer value for DML to indicate the number of rows
affected and 0 for DDL statements which do not return anything.
JDBC: ResultSet
JDBC: ResultSet

• A ResultSet consists of records.


• Each records contains a set of columns.
• Each record contains the same amount of columns, although
not all columns may have a value.
• A column can have a null value. Here is an illustration of a
ResultSet:
Creating a ResultSet

• You create a ResultSet by executing a Statement or


PreparedStatement, like this:
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from
people");
Or
String sql = "select * from people";
PreparedStatement statement =
connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
ResultSet Type, Concurrency and
Holdability
• When you create a ResultSet there are three attributes you
can set.
• These are:
1. Type
2. Concurrency
3. Holdability
ResultSet Type, Concurrency and
Holdability
Statement statement = connection.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_OVER_COMMIT
);
Iterating the ResultSet

while(result.next()) {
// ... get column values from this record
}
Accessing Column Values

• When iterating the ResultSet you want to access the column


values of each record.
• You do so by calling one or more of the many getXXX()
methods.
• You pass the name of the column to get the value of, to the
many getXXX() methods.
while(result.next()) {
result.getString ("name");
result.getInt ("age");
result.getBigDecimal("coefficient");
}
ResultSet Types

• A ResultSet can be of a certain type.


• The type determines some characteristics and
abilities of the ResultSet.
• At the time of writing there are three ResultSet
types:
1. ResultSet.TYPE_FORWARD_ONLY
2. ResultSet.TYPE_SCROLL_INSENSITIVE
3. ResultSet.TYPE_SCROLL_SENSITIVE
Navigation Methods
Method Description
absolute() Moves the ResultSet to point at an absolute position. The position is a
row number passed as parameter to the absolute() method.

afterLast() Moves the ResultSet to point after the last row in the ResultSet.

beforeFirst() Moves the ResultSet to point before the first row in the ResultSet.

first() Moves the ResultSet to point at the first row in the ResultSet.

last() Moves the ResultSet to point at the last row in the ResultSet.

next() Moves the ResultSet to point at the next row in the ResultSet.

previous() Moves the ResultSet to point at the previous row in the ResultSet.

relative() Moves the ResultSet to point to a position relative to its current


position. The relative position is passed as a parameter to the relative
method, and can be both positive and negative.
Current position of the ResultSet
Method Description
getRow() Returns the row number of the current
row - the row currently pointed to by the
ResultSet.
getType() Returns the ResultSet type.
isAfterLast() Returns true if the ResultSet points after
the last row. False if not.
isBeforeFirst() Returns true if the ResultSet points before
the first row. False if not.
isFirst() Returns true if the ResultSet points at the
first row. False if not.
ResultSet Concurrency
• The ResultSet concurrency determines whether the ResultSet
can be updated, or only read.
• A ResultSet can have one of two concurrency levels:
1. ResultSet.CONCUR_READ_ONLY
2. ResultSet.CONCUR_UPDATABLE
• CONCUR_READ_ONLY means that the ResultSet can only be
read.
• CONCUR_UPDATABLE means that the ResultSet can be both
read and updated.
Updating a ResultSet
• If a ResultSet is updatable, you can update the
columns of each row in the ResultSet.
• You do so using the many updateXXX() methods
result.updateString ("name" , "Alex");
result.updateInt ("age" , 55);
result.updateBigDecimal ("coefficient", new BigDecimal("0.1323");
result.updateRow();

result.updateString (1, "Alex");


result.updateInt (2, 55);
result.updateBigDecimal (3, new BigDecimal("0.1323");
result.updateRow();
Inserting Rows into a ResultSet

• If the ResultSet is updatable it is also possible to insert rows


into it. You do so by:
1. call ResultSet.moveToInsertRow()
2. update row column values
3. call ResultSet.insertRow()
result.moveToInsertRow();
result.updateString (1, "Alex");
result.updateInt (2, 55);
result.updateBigDecimal (3, new BigDecimal("0.1323");
result.insertRow();
result.beforeFirst();
ResultSet Holdability

• The ResultSet holdability determines if a ResultSet is closed


when the commit() method of the underlying connection is
called.
• There are two types of holdability:
1. ResultSet.CLOSE_CURSORS_OVER_COMMIT
2. ResultSet.HOLD_CURSORS_OVER_COMMIT
STORE IMAGE IN ORACLE DATABASE
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.
• public void setBinaryStream(int paramIndex,InputStream str
eam) throws SQLException
• public void setBinaryStream(int paramIndex,InputStream str
eam,long length) throws SQLException
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,“abc");
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();}
}
Example to retrieve image from
Oracle database
• 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.
• public Blob getBlob()throws SQLException
• public byte[] getBytes(long pos, int length)throws SQLExcep
tion
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()){
Blob b=rs.getBlob(2);
byte barr[]=b.getBytes(1,(int)b.length());
FileOutputStream fout=new FileOutputStream("d:\\abc.jpg");
fout.write(barr);
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}
STORE FILE IN ORACLE DATABASE
Example to store file in Oracle
database
• The setCharacterStream() method of PreparedStatement is
used to set character information into the parameterIndex.

• public void setCharacterStream(int paramIndex,InputStream


stream)throws SQLException
• public void setCharacterStream(int
paramIndex,InputStream stream,long length)throws
SQLException
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();}
}
}
RETRIEVE FILE FROM ORACLE
DATABASE
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){}
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();
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(); }
}
}
Transaction Management in JDBC

• 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.
• Isolation ensures that transaction is isolated from other
transaction.
• Durability means once a transaction has been committed, it
will remain so, even in the event of errors, power loss etc.
Transaction Management in JDBC
Transaction Management in JDBC

Method Description

It is true bydefault means each


void setAutoCommit(boolean status)
transaction is committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.


import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:orac
le:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi'
,40000)");
stmt.executeUpdate("insert into user420 values(191,'ume
sh',50000)");
con.commit();
con.close();
}}
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.
Batch Processing in JDBC

Method Description

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

It executes the batch of


int[] executeBatch()
queries.
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 user420 values(190,'abhi',40000)");
stmt.addBatch("insert into user420 values(191,'umesh',50000)");

stmt.executeBatch();//executing the batch

con.commit();
con.close();
}}

You might also like