0% found this document useful (0 votes)
93 views42 pages

Session - 2: SEED Infotech Pvt. LTD

The document provides an overview of key concepts in JDBC including transactions, calling stored procedures from Java, different ResultSet types, the Connection, Statement, ResultSet, CallableStatement, and ResultSetMetaData interfaces. It discusses batch updates, DataSources, Blob and Clob objects for storing binary and character large objects, and different types of RowSet objects like JdbcRowSet, CachedRowSet, and WebRowSet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
93 views42 pages

Session - 2: SEED Infotech Pvt. LTD

The document provides an overview of key concepts in JDBC including transactions, calling stored procedures from Java, different ResultSet types, the Connection, Statement, ResultSet, CallableStatement, and ResultSetMetaData interfaces. It discusses batch updates, DataSources, Blob and Clob objects for storing binary and character large objects, and different types of RowSet objects like JdbcRowSet, CachedRowSet, and WebRowSet.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 42

JDBC

Session - 2

SEED Infotech Pvt. Ltd.


Objectives of this Session

• Transactions & related methods in Connection


interface.
• Calling stored procedure from Java Application.
• Understanding different types of ResultSet.
• Interfaces :
 ResultSetMetaData
 DatabaseMetaData
• Batch execution.
• Blob & Clob.
• RowSet & its types.
JDBC Transactions

• What is database Transaction?

 Local Transactions.
 Distributed Transactions.

• What do we mean by Commit?

• What do we mean by Rollback?

• Can I handle Transactions through JDBC API?


Methods of Connection Interface

• public void setAutoCommit(boolean autoCommit)


throws SQLException

• public void commit() throws SQLException

• public void rollback() throws SQLException

• public Statement createStatement(int type, int


concurrency) throws SQLException
Problem Statement

• Write the Java application to call the stored


procedure written in Oracle.

Prerequisite:
Write a stored procedure in Oracle which takes
employee id as the input parameter and returns
the salary of that Employee.
Step 1 – Write Stored procedure

create or replace procedure emp_proc (v_empId


number,v_empSal out number)
as
begin
select empSal into v_empSal
from employee
where empId=v_empId;
end;
Step 2 -Get CallableStatement Object

try{
// Load Driver for Oracle.
//Get Connection
String query="{ call emp_proc (?,?) }";
CallableStatement cst=con.prepareCall(query);
}
catch(ClassNotFoundException cnfe){………}
catch(SQLException sqle){………………}
Connection Interface Revisited

• public CallableStatement prepareCall (String sql)


throws SQLException

-Creates a CallableStatement object for calling


database stored procedures.
Step 3 – Set parameter values

try
{
// Get Connection --- Refer previous code snippet.
cst.setInt(1,100);
cst.registerOutParameter(2,Types.DOUBLE);
cst.execute();
System.out.println(cst.getDouble(2));

}
catch(ClassNotFoundException cnfe){…….}
catch(SQLException sqle){…………..}
CallableStatement Interface

• public void registerOutParameter


(int parameterIndex, int sqlType) throws
SQLException

-Registers the OUT parameter in position


parameterIndex to the JDBC type sqlType.

Note: All OUT parameters must be registered


before a stored procedure is executed.
CallableStatement Interface

• public double getDouble(int parameterIndex)


throws SQLException
-Gets the value of a JDBC DOUBLE parameter
as a double in the Java programming language.

• public boolean execute() throws SQLException.


-Executes any kind of SQL statement.
Step 4 – Close the connection

try{
//Code as in previous slide
}
catch(ClassNotFoundException cnfe){…}
catch(SQLException sqle){…}
finally{
try
con.close();
}
catch(SQLException sqle){…}
}
The JDBC 2.0 API

• Two packages
 java.sql package--the JDBC 2.0 core API

 javax.sql package--the JDBC 2.0 Optional


Package API

 extends the functionality of the JDBC API from a


client-side API to a server-side API,

 it is an essential part of Java2, Enterprise


Edition technology(J2EE).
Types of ResultSet

• ‘int’ fields that are defined in ResultSet interface


to control type and concurrency of ResultSet.

• Type
 TYPE_FORWARD_ONLY
 TYPE_SCROLL_INSENSITIVE
 TYPE_SCROLL_SENSITIVE

• Concurrency
 CONCUR_READ_ONLY
 CONCUR_UPDATEABLE
Methods of ResultSet Interface

• public void first() throws SQLException

• public void last() throws SQLException

• public void previous() throws SQLException

• public void beforeFirst() throws SQLException

• Public void afterLast() throws SQLException


Methods of ResultSet Interface

• public boolean absolute () throws SQLException

• public boolean relative() throws SQLException

• public void insertRow() throws SQLException

• public void updateRow() throws SQLException

• Public void deleteRow() throws SQLException


ResultSetMetaData Interface

• Object that can be used to find out about the


types and properties of the columns in a ResultSet

• public int getColumnCount() throws


SQLException

• public String getColumnName(int column)


throws SQLException

• public int getColumnType(int column) throws


SQLException
DatabaseMetaData Interface

• Comprehensive information about the database as


a whole.
• Methods:
 public String getURL() throws SQLException

 public String getDriverName()throws SQLException

 public boolean supportsResultSetConcurrency


(int type, int concurrency) throws SQLException

 public boolean supportsResultSetType(int type)


throws SQLException
Code to update a ResultSet

try{ // -----code to get Connection Object-----


Statement stmt=con.createStatement (
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);

String query=“SELECT * FROM EMP”;


ResultSet rs=stmt.executeQuery(query);
rs.first();
rs.updateFloat(4,10000.00);
rs.updateRow();
}
catch(SQLException sqle){……….}
Code to insert a row in a ResultSet

try{ // -----code to get Statement Object-----


ResultSet rs=stmt.executeQuery(“select…”);
rs.moveToInsertRow();
rs.updateInt(1,102);
rs.updateString(2,”Joe”);
rs.updateInt(3,40);
rs.updateDouble(4,20000.00);
rs.insertRow();//inserts a row in database.
}
catch(SQLException sqle){………}
Delete Record from ResultSet & DB

try{ // -----code to get Connection Object-----


Statement stmt=con.createStatement(
ResulSet.TYPE_SCROLL_SENSITIVE,
ResulSet.CONCUR_UPDATABLE);
ResultSet rs=stmt.executeQuery(“select …..”);

//delete record from ResultSet as well as DB


rs.last();
rs.deleteRow();
}
catch(SQLException sqle)
Batch Updates

• One of the new feature provided with the


JDBC 2.0 core API.

• Set of multiple update statements that is


submitted to the database for processing as a
batch.

• Efficient than sending update statements


separately.
Batch Updates

• The Batch can contain statements for


 updating,
 inserting,
 deleting a row.
 Or DDL (create or replace)

• It can’t, however, contain a statement that


would produce a ResultSet object, such as a
SELECT statement.
Code Snippet for Batch Updates

try{
con.setAutoCommit(false);
Statement stmt = con.createStatement();

//Add queries to batch


stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);

//Execute Batch
int [] updateCounts = stmt.executeBatch();
//remaining code continues….
Code Snippet for Batch Updates

con.commit();
con.setAutoCommit(true);
} //end of try block

catch(BatchUpdateException buex) {
int [] updateCounts = buex.getUpdateCounts();
for (int i = 0; i < updateCounts.length; i++) {
System.out.print(updateCounts[i] +”\n”);
}
}
DataSource

• DataSource is a preferred means of getting a


connection to a database.

• Provide connection pooling and distributed


transactions functionality.

• DataSource is a part of the JDBC 2.0 Standard


Extension API, is essential for enterprise
database computing.
Deploying a DataSource

• Deploying a DataSource object consists of three


tasks:
 Creating an instance of the DataSource class.

 Setting its properties.

 Registering it with a naming service that uses


the Java Naming and Directory Interface
(JNDI) API.
Code Snippet for DataSource

com.dbaccess.BasicDataSource ds =null;
//Create DataSource class instance
ds=new com.dbaccess.BasicDataSource();
//set properties of datasource.
ds.setServerName("gurukul");
ds.setDatabaseName("CUSTOMER_ACCOUNTS");
ds.setDescription( "Customer accounts database for
billing”);
"The variable ‘ds’ now represents the database
CUSTOMER_ACCOUNTS installed on the server
gurukul. Any connection produced by ‘ds’ will be with
CUSTOMER_ACCOUNTS. "
Register DataSource with JNDI

• With the properties set, the system


administrator can register the BasicDataSource
object with a JNDI naming service.

//Obtain JNDI context


Context jndiCtx = new InitialContext();

//Bind the Datasource with JNDI


ctx.bind("jdbc/billingDB", ds);
DataSource

Context ctx = new InitialContext();

DataSource ds=null;
//Lookup for Database JNDI Name
ds=(DataSource) ctx.lookup("jdbc/billingDB");

//Get Connection to CUSTOMER_ACCOUNTS Table


//through datasource
Connection con = null;
con=ds.getConnection(“scott", “tiger");
Configure JDBC Connection Pool
Configure JDBC DataSource
Interface Blob and Clob

• Blob and Clob interfaces are the


representation in Java for an SQL BLOB value
and SQL CLOB value respectively.

• An SQL BLOB is a built-in database datatype


that stores a Binary Large Object as a
column value in a row of a database table.

• An SQL CLOB is a built-in database datatype


that stores a Character Large Object as a
column value in a row of a database table.
Snippet for Insertion of Image File
try
{
FileInputStream fin= null;
PreparedStatement pstat= null;

fin=new FileInputStream(“Duke.jpg”);
con.prepareStatement("INSERT into B_Tab values(?,?)");
pstat.setInt(2,id);
pstat.setBinaryStream(4,fin,(int)length);
pstat.executeUpdate();
}
catch(Exception ex){….}
RowSet

• All RowSet objects are derived from the


ResultSet interface.
• All RowSet objects are JavaBean components.
This means that they have the following:
 Properties
 The JavaBeans notification mechanism

• A RowSet object is scrollable and updatable


by default.
• All RowSet objects except JdbcRowSet are
Serializable.
Rowset Objects

• Connected RowSet Objects


 JdbcRowSet

• Disconnected RowSet Objects


 CachedRowSet

 WebRowSet
 JoinRowSet
 FilteredRowSet
JDBCRowSet

• Enhanced ResultSet object.

• The big difference is that it has a set of


properties and a listener notification
mechanism that make it a Java Bean
component.

• One of the main uses of a JdbcRowSet object is


to make a ResultSet object scrollable and
updatable when it does not otherwise have
those capabilities.
CachedRowSet

• CachedRowSet object has all the capabilities of


a JdbcRowSet object plus it can also do the
following:
 Obtain a connection to a data source and
execute a query.
 Read the data from the resulting ResultSet object
and populate itself with that data.
 Manipulate data and make changes to data
while it is disconnected.
 Reconnect to the data source to write changes
back to it.
 Check for conflicts with the data source and
resolve those conflicts.
WebRowSet

• A WebRowSet object is an extension of


CachedRowSet object plus it can also do the
following:

 Write itself as an XML document.


 Read an XML document that describes a
WebRowSet object
JoinRowSet

• A JoinRowSet object has all the capabilities of a


WebRowSet object (and therefore also a
CachedRowSet object) plus it can also do the
following:

 Form the equivalent of an SQL JOIN without


having to connect to a data source
FilteredRowSet

• A FilteredRowSet object likewise has all the


capabilities of a WebRowSet object (and
therefore also a CachedRowSet object) plus it
can also do the following:

 Apply filtering criteria so that only selected data


is visible. This is equivalent to executing a query
on a RowSet object without having to use a query
language or connect to a data source.
Summary

• Connection interface provides methods related


to Transaction Management.
• CallableStatement interface is used for calling
a Stored Procedure from JDBC Application.
• Different types of ResultSet.
• ResultSetMetaData & DatabaseMetaData
interface.
• Batch Update Feature
• Blob & Clob implementation
• RowSet & its various types

You might also like