0% found this document useful (0 votes)
8 views46 pages

JDBC Connectivity

jdbc concepts in java
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)
8 views46 pages

JDBC Connectivity

jdbc concepts in java
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/ 46

JAVA DATA-BASE CONNECTIVITY

 Java as database front-end


Ø Database client/server methodology
Ø Two-Tier Database Design
Ø Three-Tier Database Design
 The JDBC API
Ø The API Components
Ø Limitations Using JDBC (Applications vs. Applets)
Ø Security Considerations
Ø A JDBC Database Example
Ø JDBC Drivers
Ø JDBC-ODBC Bridge
Ø Current JDBC Drivers
Java as Database Front End

Java offers several benefits to the developer creating


a front-end application for a database server.
Java is ‘Write Once Run Everywhere’language.
This means that Java programs may be deployed
without recompilation on any computer architectures
and operating systems that possesses a Java Virtual
Machine.
The Sun Microsystems met the challenge in 1996
with the creation of JDBC driver for JDBC API.
Both were created out of necessity, because until
then Java wasn’t industrial strength programming
language since Java was unable to access the DBMS.
The JDBC driver developed by Sun wasn’t driver at all.
DBMS manufacturers and third-party vendors encouraged
to build JDBC drivers that confirmed to Sun’s specifications.
This meant that Java programmer could use high- level
Java data-objects defined in the JDBC API to write a routine
that interacted with the DBMS.
Java data objects convert the routine into low-level
message that conform to the JDBC driver specification and
send them to the JDBC driver.
The JDBC driver translates the routine into low-level
messages that understood and processed by DBMS.
DATABASE CLIENT-SERVER
METHODOLOGY
Relational databases are the most common
DBMS.
 A main characteristic of a relational database is
the absolute separation between physical and
logical data.
 Data is accessed through the associated logical
model to avoid supplying physical storage
locations and to reduce the limitations imposed
by using physical information.
DATABASE CLIENT/SERVER
ARCHITECTURE
SOFTWARE ARCHITECTURES
 The first generation of client-server architectures is
called two-tiered.
 It contains two active components: the client, which
requests data, and the server, which delivers data.
 separately for database queries and updates, and for
user interface presentations.
 Usually the network binds the back end to the front
end, although both tiers could be present on the same
hardware.
 For example, hundreds or thousands of airline seat
reservation applications can connect to a central
DBMS to request, insert, or modify data.
 While the clients process the graphics and data entry
validation, the DBMS does all the data processing.
…… CONTINUE
 Actually, it is inadvisable to overload the
database engine with data processing that is
irrelevant to the server, thus some processing
usually also happens on the clients. The typical
client-server architecture
Fig. Two-tier client server architecture

Client

Java Database Server


Application/
JDBC
 The two tiers are often called as Application layer
includes JDBC drivers, business logic and user
interfaces whereas second layer i.e. Database layer
consists of RDBMS server.
 Advantages:

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

 In three-tiered architectures, most of the


business logic is frozen in the middle tier.
 In this architecture, when the business
activity or business rules change, only the
middleware must be modified.
ADVANTAGES :
Flexible: It can change one part without affecting
others.
It can connect to different databases without
changing code.
Specialization: presentation / business logic / data
management.
It can cache queries.
It can implement proxies and firewalls
Drawbacks:-
Higher complexity
Higher maintenance
Lower network efficiency
More parts to configure (and buy)
WHAT IS JDBC?
 The JDBC stands for Java Database Connectivity.
 It’s a specification for using data sources in Java
applets and applications.
 It’s an API for using low-level JDBC drivers.

 It’s an API for creating the low-level JDBC drivers,


which do the actual connecting/transacting with data
sources.
 It’s based on the X/Open SQL Call Level Interface
(CLI) that defines how client/server interactions are
implemented for database systems.
 The JDBC defines every aspect of making data-aware
Java applications and applets.
WHAT IS ODBC?
 Microsoft established a common standard for communicating
with databases called Open Database Connectivity that is,
ODBC.
 Until ODBC,most database clients were server-specific.
 ODBC drivers abstract away vendor-specific protocols,
providing a common API to database clients.
 By writing our database clients to the ODBC API, we enable
our programs to access more database servers.
 JDBC provides a common database programming API for Java
programs.
 However, JDBC drivers do not directly communicate with as
many database products as ODBC drivers.
 Instead, many JDBC drivers communicate with database
using ODBC. In fact, one of first JDBC drivers was the JDBC-
ODBC bridge driver developed by JavaSoft.
JDBC ARCHITECTURE

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

 This type of driver wraps a native API with Java


classes.
 The Oracle Call Interface (OCI) driver is an
example of a Type 2 driver. Because a Type 2
driver is implemented using local native code, it
is expected to have better performance than a
pure Java driver.
 These drivers enable JDBC programs to use
database-specific APIs (normally written in C or
C++) that allow client programs to access
databases via the Java Native Interface.
 This driver type translates JDBC into database-
specific code.
 Type 2 drivers were introduced for reasons
similar to the Type 1 ODBC bridge driver.
TYPE 2 DRIVE
TYPE 3 DRIVER: NETWORK PROTOCOL, PURE JAVA
DRIVER
 These drivers take JDBC requests and translate them into a
network protocol that is not database specific.
 These requests are sent to a server,which translates the database
requests into a database-specific protocol.
 This type of driver communicates using a network protocol to a
middle- tier server. The middle tier in turn communicates to the
database.
 Oracle does not provide a Type 3 driver. They do, however, have a
program called Connection Manager that, when used in
combination with Oracle's Type 4 driver, acts as a Type 3 driver in
many respects.
TYPE 4 DRIVER: NATIVE PROTOCOL, PURE
JAVA DRIVER
 These convert JDBC requests to database-specific network
protocols, so that Java programs can connect directly to a
database.
 This type of driver,written entirely in Java, communicates
directly with the database.
 No local native code is required. Oracle's thin driver is an
example of a Type 4 driver.
THE JDBC API
 The JDBC API is contained in two packages named java.sql and javax.sql. The java.sql
package contains core Java objects of JDBC API.
 There are two distinct layers within the JDBC API: the application layer, which database-
application developers use and driver layer which the drivers vendors implement.
The connection between application and driver layers is illustrated in figure below:

DriverManager

Driver

Connection

PreparedStatement Statement Callable Statement

ResultSet Resultset ResultSet


THE JDBC PROCESS
Accessing JDBC / ODBC Bridge with the database
Before actual performing the Java database application, we associate the
connection of database source using JDBC – ODBC Bridge.
The steps are as follows:
 Go to Control Panel -> Administrative Tools -> Data Sources.
 Open Data Sources ODBC icon.

 Select the tab with heading “User DSN”.


 Click on ‘Add’ button.
 Select the appropriate driver as per the database to be used. (e.g.
Microsoft ODBC driver for Oracle to access Oracle Database
 Click finish button and the corresponding ODBC database setup window
will appear.
 Type DSN name and provide the required information such as user name
and password for the database (.mdb files) of Microsoft Access Database etc.
and click on OK button.
 Our DSN name will get appeared in user data sources.
 There are six different steps to use JDBC in our
Java application program.
Phase Task Relevant java SQL classes
instalization Load driver Drivemanager
Create Connection Connection

Processing Generate SQL Stmt ResultSet


stmt Process
Result data

Termination Terminate connection Connection


Release data structure stmt
 Load the driver
 Define and establish the Connection.

 Create a Statement object

 Execute a query

 Process the results

 Close the connection


 Loading the JDBC driver
Ø The JDBC drivers must be loaded before the Java
application connects to the DBMS. The Class.forName() is
used to load the JDBC driver. The developer must write
routine that loads the JDBC / ODBC Bridge. The bridge
driver called sun.jdbc.odbc.JdbcOdbcDriver. It is done in
following way:
Ø Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
 Define and establish the Connection
Ø After loading the driver the application must get connected
to DBMS. For this we use DriverManager.getConnection()
method. The DriverManager is highest class in Java.sql
hierarchy and is responsible for managing driver related
information.
Ø Connection DriverManager.getConncetion(String url,
String userID, String password);
Ø Here, the URL format is specified as follows:
<protocol>:<subprotocol>:<dsn-name>
 e.g jdbc:odbc:customer Conncetion con;
 con = DriverManager.getConnection(“jdbc:odbc:customer”,
Ø micro”, “pitch”);
 Create a Statement object
Ø The createStatement( ) method of Connection interface is
used to create the Statement object which is then used to
execute the query. For example:
Statement st = con.createStatement();
 Execute a query
Ø The executeQuery() method of Statement object is used
execute and process the query which returns the ResultSet
object. ResultSet is the object which actually contains the
result returned by the query. For example:
Ø ResultSet rs = st.executeQuery(“select * from customer”);
 Process the results
Ø The ResultSet object is assigned the results received from the DBMS
after the query is processed. The ResultSet object consists of methods
used to interact with data that is returned by the DBMS to Java
application program.
Ø For example, the next() method is used to proceed throughout the
result set. It returns true, if the data is available in result set to read.
Ø The ResultSet also contains several getXxx( ) methods to read the
value from particular column of current row.
For example, getString(“name”) will read the value from column
‘name’ in the form of string. Instead of passing column name as
parameter, we can pass column as parameter also. Such as,
getString(1).
For example:
String name;
int age;
do{
name = rs.getString(“name”);
age = rs.getInt(“age”);
System.out.println(name+“=”+age); }While(rs.next());
 Close the connection
Ø The Connection to the DBMS is terminated by using the close()
method of the Connection object once Java program has finished
accessing the DBMS.
con.close();
STATEMENT OBJECTS
 executeQuery()
Ø This method returns the ResultSet object that
contains rows, columns and metadata that represent
data requested by the query. Its signature is:
Ø ResultSet executeQuery(String 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.

You might also like