JDBC Connectivity
JDBC Connectivity
Client
It is simple in design.
Client-side scripting offloads work onto the client
Drawbacks:
Fat client.
It is inflexible.
Although the two-tiered architecture is common,
another design is starting to appear more frequently.
To avoid embedding the application’s logic at both the
database side and the client side, a third software tier
may be inserted.
FIG. THREE-TIER CLIENT/SERVER ARCHITECTURE
Java JDBC Database
Application Server
13
Network
GENERAL ARCHITECTURE
14
The JDBC is two-dimensional.
The reasoning for the split is to separate the low-level
programming from the high-level application interface.
The idea is that database vendors and third-party software
vendors will supply pre-built drivers for connecting to different
databases.
JDBC drivers are quite flexible: They can be local data sources or
remote database servers.
The implementation of the actual connection to the data
Source/database is left entirely to the JDBC driver.
The goal of the JDBC is a DBMS independent interface, a
“generic SQL database access framework,” and a uniform
interface to different data Sources.
The programmer writes only one database interface; using JDBC,
the program can access any data source without recoding.
JDBC DRIVERS
Sun has defined four categories of JDBC drivers. The
categories delineate the differences in architecture for the
drivers.
One difference between architectures lies in whether a
given driver is implemented in native code or in Java code.
Native code means whatever machine code is supported by
a particular hardware configuration. For example, a driver
may be written in C and then compiled to run on a specific
hardware platform.
Another difference lies in how the driver makes the actual
connection to the database.
The four driver types are :
Type 1 Driver: JDBC/ODBC Bridge
Type 2 Driver: Native API Driver
Type 3 Driver: Network Protocol, Pure Java Driver
Type 4 Driver: Native Protocol, Pure Java Driver
TYPE 1 DRIVER: JDBC/ODBC BRIDGE
This type uses bridge technology to connect a Java
client to a third-party API such as Open DataBase
Connectivity (ODBC).
Sun's JDBC-ODBC bridge is an example of a Type 1
driver.
These drivers are implemented using native
code.
This driver connects Java to a Microsoft ODBC (Open
Database Connectivity) data source.
This driver typically requires the ODBC driver to be
installed on the client computer and normally requires
configuration of the ODBC data source.
The bridge driver was introduced primarily to allow
Java programmers to build data-driven Java
applications before the database vendors had Type 3
and Type 4 drivers.
TYPE 1 DRIVER
TYPE 2 DRIVER: NATIVE API DRIVER
DriverManager
Driver
Connection
Execute a query
executeUpdate()
Ø This method is used to execute the queries that
contain INSERT, DELETE and UPDATE statements.
This method returns integer indicating the number of
rows that were updated by the query.
Ø Its signature is: int executeUpdate(String query);
Ø For example:
int rows = st.executeUpdate("DELETE FROM
EMPLOYEES WHERE STATUS=0");
execute()
Ø It executes the given SQL statement, which may return
multiple results.In some (uncommon) situations, a single
SQL statement may return multiple result sets and/or
update counts we must then use the methods getResultSet( )
or getUpdateCount( ) to retrieve the result, and
getMoreResults( ) to move to any subsequent result(s).
Signature is as follows:
Ø public boolean execute(String sql)
For example:
if(st.execute())
rs = st.getResultSet();
Signatures of other methods:
public ResultSet getResultSet()
public int getUpdateCount()
public boolean getMoreResults()
PREPAREDSTATEMENT OBJECT
A SQL query must be compiled before the DBMS processes
the query.
A SQL query can be precompiled and executed by using the
PreparedStatement object.
In such cases a query is created similar to other queries.
However, a question mark is given on the place for the
value that is inserted into the query after it is compiled. It
is the value that changes each time the query is executed.
“select * from nation where population > ?”
Such type of the query is passed as the parameter to the
prepareStatement( ) method of the Connection object which
then returns the PreparedStatement object. For example:
String query = “select * from nation where population > ?”;
PreparedStatement ps = prepareStatement(query);
Once the PreparedStatement object is obtained, the setXxx(
) method it can be used to replace question mark with the
value passed to setXxx()
ps.setInt(1, 100000);
THE SETXXX( ) METHODS:
void setBoolean(int index, boolean value);
void setByte(int index, byte value);
void setDate(int index, Date value);
void setDouble(int index, double value);
void setFloat(int index, float value);
void setInt(int index, int value);
void setLong(int index, long value);
void setObject(int index, Object value);
void setShort(int index, short value);
void setString(int index, String value);
Example:
Consider the following database:
import java.sql.*;
class StudentData {
public static void main(String args[]){
Try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:stud");
PreparedStatement ps = con.prepareStatement("select *
from Student where Marks > ?");
ps.setInt(1,70); //set question marks place holder
ResultSet rs = ps.executeQuery(); //execute
System.out.println("Students having marks > 70 are:");
while(rs.next())
System.out.println(rs.getString(2));
con.close(); }
catch(Exception e){ } }}
Output:
Students having marks > 70 are:
Rakhee
Rahul
Karthik
CALLABLESTATEMENT OBJECT
The CallableStatement is used to call the stored procedures from
within a JDBC application program. A stored procedure is a
block of code and is identified by a unique name. The type style
of code depends upon the DBMS vendor and can be written in
PL/SQL, Transact-SQL, C or another programming language.
The stored procedure is executed by invoking name of the stored
procedure.
For example, a stored procedure written in PL/SQL
CREATE PROCEDURE sp_interest (id IN INTEGER,bal IN OUT FLOAT) IS
BEGIN
SELECT balance
INTO bal
FROM account
WHERE account_id = id;
bal := bal + bal * 0.03;
UPDATE account
SET balance = bal
WHERE account_id = id;
END;
The CallableStatement object uses three types of parameters when calling
a stored procedure. These parameters are IN, OUT, INOUT. The IN
parameter contains the data that needs to be passed to the stored
procedure whose value is assigned using setXxx() method. Whereas, OUT
parameter contains the value returned by the stored procedure, if any. The
OUT parameter must be registered using registerOutParameter() method
and afterwards this is retrieved by using getXxx() method. The INOUT
parameter is a single parameter that is used to both pass information and
retrieve information from a stored procedure.
public void registerOutParameter(int parameterIndex, int sqlType)
Try {
CallableStatement statement;
statement = c.prepareCall("{call sp_interest(?,?)}");
statement.registerOutParameter(2, java.sql.Types.FLOAT);
statement.setInt(1, 310);
statement.execute( );
System.out.println("New balance:" + statement.getFloat(2));
}
statement.close( );
c.close( );
RESULTSET
A ResultSet contains all of the rows which satisfied
the conditions in an SQL statement, and it provides
access to the data in those rows through a set of get
methods that allow access to the various columns of
the current row.
The ResultSet.next( ) method is used to move to the
next row of the ResultSet, making the next row
become the current row.
The general form of a result set is a table with
column headings and the corresponding values
returned by a query
The getXXX( ) methods provide the means for
retrieving column values from the current row in a
ResultSet
Either the column name or the column number can
be used to designate the column from which to
retrieve data.
For example, if the second column of a ResultSet object is
named “title”, to retrieve the value stored in that column,
use:
String s = rs.getString("title"); (or)
String s = rs.getString(2);
Methods such as getString, getBigDecimal, getBytes,
getDate, getTime, getTimestamp, getObject, getByte,
getShort, getInt, getLong, getFloat, getDouble and
getBoolean are available in the ResultSet to receive the data
in the appropriate type.
Information about the columns in a ResultSet is available
by calling the method getMetaData( ).
The ResultSetMetaData object returned gives the number,
types, and properties of its ResultSet object's columns.
To get the column names and type :
ResultSetMetaData rsm = rs.getMetaData( );
for (int I =1; I < rsm.getColumnCount( ); I++)
System.out.println(“Column : ”+ rsm.getColumnName(I) +
“is of Type : ” + rsm.getColumnTypeName(I));
FOLLOWING GET METHODS ARE USED IN RESULTSET:
boolean getBoolean(int columnIndex) boolean getBoolean(String olumnName)
byte getByte(int columnIndex) byte getByte(String columnName)
Date getDate(int columnIndex) Date getDate(String columnName)
double getDouble(int columnIndex) double getDouble(String columnName)
float getFloat(int columnIndex) float getFloat(String columnName)
int getInt(int columnIndex) int getInt(String columnName)
long getLong(int columnIndex) long getLong(String columnName)
double getDouble(int columnIndex) double getDouble(String columnName)
Object getObject(int columnIndex)
Object getObject(String columnName)
short getShort(int columnIndex)
short getShort(String columnName)
String getString(int columnIndex)
String getString(String columnName)
Time getTime(int columnIndex)
Time getTime(String columnName)
import java.sql.*; class StudentData {
public static void main(String args[]) {
Try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:stud");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from Student");
System.out.println("The Database is:-");
System.out.println("Roll\tName\t\tMarks Pass Birth-Date");
System.out.println("=====================================");
while(rs.next()) { int roll = rs.getInt(1); String name = rs.getString(2);
int marks = rs.getInt("Marks"); boolean pass = rs.getBoolean(4); Date d = rs.getDate(5);
System.out.printf("%-5d",roll); System.out.printf("%-10s",name); System.out.printf("%-
6d",marks);
if(pass) System.out.printf("Yes "); else System.out.printf("No "); System.out.printf("%-
15s\n",d.toString()); con.close(); }
catch(Exception e){ }
}
}
Output: The Database is:-
Roll Name Marks Pass Birth-Date
=====================================
1 Rakhee 75 Yes 1990-12-14
2 Amit 38 No 1990-10-02
3 Ajita 63 Yes 1989-01-24
4 Rahul 78 Yes 1990-01-01
5 Minal 67 Yes 1991-02-12
6 Karthik 71 Yes 1988-07-06
METADATA
Metadata is nothing but data about data.
Database name, table name, column name,
column attributes, and other information that
describes database components are known as
Metadata
Metadata is used by JDBC application to identify
database components without needing to know
details of a column, the table or the database..
JDBC provides two meta-data interfaces:
java.sql.ResultSetMetaData
java.sql.DatabaseMetaData.
getDatabaseProductName() It returns product name of
database
getDatabaseProductVersion() It returns product version of
database
getUserName() It returns the user name
getURL() It returns URL of database
getSchemas() It returns schema names available in
database
getPrimaryKeys() It returns primary keys
getProcedures() It returns stored procedure names
getTables() It returns names of tables in database
MAPPING TYPES JDBC - JAVA
RMI
RMI can be used to to transparently transmit
objects from one server to another .
RMI can easily programmed to act as a proxy
service to a database by setting up a listener
process to handle access requests from clients.
RMI can invoke a set of methods that make the
request to the database on behalf the client.
Advantages
Ø It is an all java solution , making it ideal for applet
Ø It is a non proprietary solution.
Ø It maintained the persistent connection with the database.
Ø Disadvantage
Ø An RMI application can require more time & expertise to
implement.
Ø Object serilization is can requried significant server resources for
large object
COMMON OBJECT REQUEST BROKER
ARCHITECTURE (CORBA)
This technology is the open standard for Heterogeneous computing.
CORBA complements the JavaTM platform by providing a
distributed object framework, services to support that framework,
and interoperability with other languages.
The Java platform complements CORBA by providing "Write Once,
Run AnywhereTM" portability, a highly productive implementation
environment, and a very robust platform
CORBA standards provide the proven, interoperable infrastructure
to the Java platform. IIOP (Internet Inter-ORB Protocol) manages
the communication between the object components that power the
system.
The Java platform provides a portable object infrastructure that
works on every major operating system. CORBA provides the
network transparency, Java provides the implementation
transparency.