Vous êtes sur la page 1sur 26

JDBC-Overview

JDBC-Overview

JDBC-Overview

Abstract
This Document is intended to achieve the goal to get a generic idea on Overview of the
JDBC Concepts and its new features.

JDBC-Overview

CONTENTS
INTRODUCTION..........................................................................................................................................6
JDBC ARCHITECTURE............................................................................................................................7
JDBC DRIVER TYPES..............................................................................................................................8
SAMPLE PROGRAMS...........................................................................................................................10
JDBC EXCEPTION TYPES AND EXCEPTIONAL HANDLING...............................................17
SQL EXCEPTION METHODS.............................................................................................................20
NEW FEATURES..................................................................................................................................... 21
REFERENCES.2
6

JDBC-Overview

Introduction
This Document provides all concepts of JDBC, Types of Drivers, JDBC Exception Types
and JDBC Exceptional Handling & New Features of JDBC 3.0.

JDBC-Overview

Introduction:
Database has proved to be an efficient way of organizing and storing data. Among many
ways of organizing data, RDBMS is tine most popular style where data is organized in the
form of tables, e.g. Oracle, MS SQL-Server, MySQL, DB2 are some of the popular
RDBMS used in the industry.
In order to use a database, we have to send commands using a language-called SQL
(Structured Query Language). A database protocol is a set of rules which are used to
interact with the database over network. The protocol is different for every database server
although all of them can understand SQL.
JDBC is a standard Java API to interact with relational databases. The classes and
interfaces of JDBC are used by us to write Java applications for interacting with relational
database. The interfaces of JDBC will be implemented by the vendors usually the database
vendor provides the implementation of JDBC interfaces although Independent Software
Vendor, (third party) can also provide such implementation. The vendor implementation
consists of many classes and is generally provided in the form of a jar File which we have
to keep in the CLASSPATH during runtime.
The JDBC API implementations are popularly termed as JDBC Driver / JDBC Provider.
Irrespective of the Driver chosen, the application remains the same since all drivers
implement common Interfaces. A JDBC driver implemented for a database cannot be used
for other databases_ since every database has its own proprietary protocol, i.e. JDBC
Driver for Oracle is different from JDBC Driver for SQL Server.

JDBC Architecture:
Driver Manager is a class which acts as a helper and performs the initial activity to
establish connection with the database. We request a Driver Manager to provide
connection by giving a string which is known as JDBC URL
1. Driver Recognition Information
2. Database Location Information
More: The way JDBC URL is written for a particular driver should be given to us by the
driver vendor in some form of documentation.
The Driver recognition information will be used to decide the driver and such driver will
be asked to establish connection by providing the database location information,(which is
also there in the URL). The established connection will_be_passed_on to the application.
We do not need the services of driver or driver manager again unless, we need to establish
another connection.
For DriverManager to choose an appropriate driver, it mist-be aware of the existing drivers
in the environment. The Driver Manager is aware of the driver since the JDBC Driver
registers itself, with the Manager. A JDBC Driver is expected to register itself with the
Manager whenever the Driver class is loaded. We can explicitly load the driver class using
the following static method Class.forName (String)

JDBC-Overview

JDBC ARCHITECTURE

JDBC-Overview
JDBC Driver Types:
JDBC drivers fit into one of the following four categories:
Type 1 Driver (JDBC-ODBC Bridge plus ODBC driver)

ODBC is a standard used in non Java world for interacting with relational databases. The
implementation of ODBC API is called as ODBC Driver, which will be a native library on
our platform. Type-I JDBC Driver maps the JDBC methods into ODBC function calls.

Type-I advantage:
We can interact with almost any database since the databases are bound to have ODBC
drivers due to the popularity of the API.
Drawbacks of Type-I Strategy:
The application is no longer pure Java since ODBC driver is a native library. Security may
be compromised since the security manager of JVM does not scrutinize the native: code.
We need to explicitly install the ODBC driver and configure a DSN (Data Source Name)
on the machine where we wish to run the application. ODBC DSN is a Data Structure
which consists of following information
1. The ODBC Driver
2. The Database Location Information
User DSN and System DSN details are stored in Windows registry whereas tile DSN is
saved in a file. Type-I JDBC driver bundled with JDK does not recognize file DSN
therefore we should create user DSN or System DSN. User DSN can be only used by the
user who created it where as system DSN can be used by any user on the system.

JDBC-Overview

Type-II JDBC Driver (Partly Java-Partly Native JDBC Driver):


t

Some database vendors provide alternate API to ODBC for their database. For example:
Oracle provides OCI as alternate to ODBC. The implementation of such API will be in
native library (e.g.: DLL in case of Win OS) which must be installed on client machine
and configured in suitable manner as per the client configuration utility provided by the
vendor.
If a JDBC Driver uses such alternate API's for database interactions then it qualifies as
Type-II Driver.

For example: Oracle provides OCT-JDBC Driver which interacts with OCI library to talk
to the database.

Type-Ill Driver (Network Protocol JDBC Driver):


The JDBC driver will rely on a network server for DB Interactions.
The advantages of such approach are
1. They are useful in environments where we do not have direct connectivity facility
with the host where database is running.
2. Since the network server is the central access for all the clients, we can restrict the
number of simultaneous connections and thereby use the database in an optimal
manner.
3. The network server can implement data caching and reduce the actual number of
trips to database hence improving the performance.
4. Callback concepts can be implemented where the server can notify the client about
the changes to the data.

WebLogic Server provides implementation for Type III kind of JDBC drivers. Such driver
interacts with the server using Java RMI technology.

Type IV JDBC Driver (Pure Java JDBC Driver):


This kind of driver directly interacts with the database over TCP/IP protocol. Such drivers
are light weight and hence are the most preferred kind of drivers.

JDBC-Overview

Sample Programs
DBDemo2.java----Connecting to mysql DB through Java

import java.sql.*;
import java.util.*;
Public class DBDemo2
{
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/test";
Properties p = new Properties
p.put("user", "root");
p.put("password" , "dss");
CIass.forName("com.rnysql.jdbc.Driver"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn = DriverManager.getConnection (url.p);
System.out.println ("Connection Established"):
conn.close ();
}
}

JDBC-Overview

DBDemoCreate.Java----How to Create a table in mysql DB through Java?


Import java.sql.*;
public class DBDemoCreate;
{

public static void main (String[] args) throws Exception


{
String url = "jdbc: mysql: //localhost:3306/test";
String username = "root";
String password = "dss";
Class.forName ("com.mysql.jdbc.Driver"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn =DriverManager.getConnection (url, username, password);
String dropCommand ="DROP TABLE IF EXISTS emp";
String createCommand = "CREATE TABLE Emp" +" empno INTEGER PRIMARY
KEY," + ename VARCHAR (20)," + sal
DOUBLE (7, 2)" +")";
Statement stm = conn.createStatement ();
stm.execute (dropCommand);
stm.execute (createCommand);
System.out.println ("Table Created");
stm.closeO;
conn.close ();
}
}

JDBC-Overview

DBDemoInsert.java ---- How to Insert into a table in mysql DB through Java?

Import java.sql.*;
public class DBDemoInsert
{
public static void main (String [] args) throws Exception
{
String url = "jdbc: mysql: //localhost:3306/test"; String username = "root";
String password = "dss";
Class.forName ("com.mysql.jdbc.Driver"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn = DriverManager.getConnection (urI, username, password);
String insertCommand = "INSERT INTO emp VALUES (101,'Abc', 12500.00)";
Statement stm = conn.createStatementO;
int count = stm.executeUpdate (insertCommand);
System.out.println (count + row(s) inserted");
stm.close ()
conn.close()
}
}

JDBC-Overview

DBDemoResultSetMetaDatajava---How to use select query from Java to get


metadata?
importjava.sql.*;
public class DBDemoResultSetMetaData
public static void main(String[] args) throws Exception
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "dss";
Class.forName ("com.mysql.jdbc.Driver"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn = DriverManager.getConnection (url, username, password);
Statement stm = conn.createStatementO;
String query = "SELECT empno, ename,sal FROM emp WHERE 1 =2;
ResultSet rs = stm.executeQuery (query);
ResultSetMetaData rm = rs.getMetaData ();
int cols = rm.getColumnCountO;
for (int i=l; i<=cols; i++)
{
System.out.print (rm.getColumnName (i) + "\t");
System.out.print (rm.getCoIumnType (i) + "\t");
System.out.print (rm. getColumnTypeName (i) + "\t")
System.out.println (rm.getColumnClassName(i));
}
rs.close ();
Stm.close ();
Conn.close ();
}
}

JDBC-Overview
DBDemoSelect.java--- How to use select query from Java to retrieve values?
import java.sql.*;
public class DBDemoSelect
{
public static void main (String[] args) throws Exception
{
String url = "jdbc: mysql: //localhost:3306/test";
Suing username = "root";
String password = "dss";
Class.forName ("com.mysql.jdbc.Driyer"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn = DriverManager.getConnection (url, username, password);
Statement stm = conn.createStatement ();
String query= "SELECT empno, ename, sal FROM emp";
ResultSet rs = stm.executeQuery (query);
ResultSetMetaData rm= rs.getMetaData ();
int cols= rm.getColumnCount ();
System.out.println ();
for (int i=l; i<=cols; i++)
{
System.out.print (rm.getColumnName (i) + "\t");
}
while (rs.next ())
for (int i=l; i<=cols; i++)
{
System.out.print (rs.getString (i) + "\t");
}
System.out.println ();
}
rs.close (); stm.close ();
conn.close ();
}

JDBC-Overview
}

DBDemoDelete.java ----How to delete from a table ?


import java.sql.*;
public class DBDemoDelete
{
public static void main (String [] args) throws Exception
{
String url = "jdbc: mysql: //localhost:3306/test";
String username = "root";
String password = dsr";
Class.forName ("com.mysqI.jdbc.Driver"); //.set mysql-connector-java-5.0.7-i) in. jar in
classpath
Connection conn = DriverManager.getConnection (ur], username, password):
String deleteCommand - "DELETE FROM emp"
Statement stm = conn.createStatement ();
int count = stm.executeUpdate (deleteCommand );
System.out.println (count +" row(s) deleted");
conn.close ();
}
}

JDBC-Overview
DBDemoUpdate.javaHow to update a table?
import java.sql.*;
public class DBDemoUpdate
{
public static void main (String[] args) throws Exception
{
String url = "jdbc: mysql: //localhost:3306/test";
String username = "root";
String password = "dss";
Class.forName ("com.mysql.jdbc.Driver"); // set mysql-connector-java-5.0.7-bin.jar in
classpath
Connection conn = DriverManager.getConnection (url,username,password);
String updateCommand = "UPDATE emp SET ename = 'Pop', sal = 18888 WHERE
empno = 103";
Statement stm = conn.createStatement();
int count = stm.executeUpdate ( updateCommand);
System.out.println (count + " row(s) updated");
stm.closeQ;
conn.closeQ;
}
)

JDBC-Overview

JDBC Exception Types and Exception Handling


SQL Exceptions
Many of the methods in the java.sql package throw a SQLException, which requires a
try/catch block like any other Exception. Its purpose is to describe database or driver errors
(SQL syntax, for example). In addition to the standard getMessage () inherited from
Throwable, SQLException has two methods which provide further information, a method
to get (or chain) additional exceptions and a method to set an additional exception.
getSQLState () returns an SQLState identifier based on the X/Open SQL
specification. Your DBMS manuals should list some of these or see Resources for
information to find SQLStates.
getErrorCode () is provided to retrieve the vendor-specific error code.
getNextException() retrieves the next SQLException or null if there are no more.
Many things can go wrong between your program and the database. This method
allows tracking all problems that occur.
setNextException() allows the programmer to add an SQLException to the chain.
These methods should be fairly straightforward. Typical catch code would look similar to
the following:
try
{
// some DB work
} // end try
catch ( SQLException SQLe)
{
while( SQLe != null)
{
// do handling
SQLe = SQLe.getNextException();
}
} // end catch
Tip: Programmers are often perplexed by syntax errors, which seem to refer to some
invisible operation, like "ungrok found at line 1, position 14." Consistently reporting the
output of Connection.nativeSQL (yourQueryString) in exception handlers will clarify
matters.

JDBC-Overview
SQL Warnings
An SQLWarning is a subclass of SQLException, but is not thrown like other exceptions.
The programmer must specifically ask for warnings. Connections, Statements, and
ResultSets all have a getWarnings() method that allows retrieval. There is also a
clearWarnings() method to avoid duplicate retrievals. The SQLWarning class itself only
adds the methods getNextWarning () and setNextWarning ().
An SQLWarning is very similar to traditional compiler warnings: something not exactly
right occurred, but its effect was not severe enough to end processing. Whether it is
important enough to investigate depends on the operation and context. An example of an
SQLWarning is mentioned in the Scrollable Result Set section.
Statements clear warnings automatically on the next execution. ResultSets clear warnings
every time a new row is accessed. The API documentation is silent regarding Connection;
to be cautious, issue clearWarnings () after warnings are obtained.
Typical code for obtaining SQLWarnings looks similar to this:
try
{
...
stmt = con.createStatement();
sqlw = con.getWarnings();
while( sqlw != null)
{
// handleSQLWarnings
sqlw = sqlw.getNextWarning();
}
con.clearWarnings();
stmt.executeUpdate( sUpdate );
sqlw = stmt.getWarnings();
while( sqlw != null)
{
// handleSQLWarnings
sqlw = sqlw.getNextWarning();
}
} // end try
catch ( SQLException SQLe)
{
...
} // end catch

JDBC-Overview
LOBs
JDBC 2.0 includes classes for handling several SQL3 data types. This section discusses
LOBs or Large Objects. Two types of LOBs are defined: BLOBs--Binary Large Objects
and CLOBs--Character Large Objects.
From the perspective of classic relational database theory, a Clob is a marginal type--a lot
of characters--and a Blob isn't really a type at all; all that is known is that the Blob contains
some number of bytes, which could be anything. It should be clear that this tends to defeat
the notion of data independence, particularly when there are other very acceptable methods
for using a database to track what are essentially graphics, audio, or other types of binary
files. Notice that there is no mechanism to prevent you from, say, writing an audio file to
what is supposed to be an image Blob, or to know the name of the original source, or any
number of similar considerations.

Locators
An SQL Locator type is similar in concept to a pointer or other information that keeps track
of an entity. JDBC developers don't have to deal with locators, but it is helpful to
understand the concept, because a locator is really what a JDBC driver expects to find in an
Array, Blob, or Clob column. That is, the actual data is not brought down in the ResultSet,
just the locator. You specifically ask for the LOB data to be returned as needed, which is
called materializing the data. Clearly this is more efficient than bringing down unknown
quantities of bytes for each column. The actual data is stored to and retrieved from
'somewhere else' by the DBMS.

Clob
A Clob is a JDBC interface mapping for an SQL CLOB. A Clob is obtained by one of the
getClob () methods of a ResultSet or CallableStatement. A Clob has methods to get a
substring of the data, the length of the data, and the position of another Clob or a String in
the current Clob. These methods work without materializing the data. To materialize the
data, one can use getAsciiStream () or getCharacterStream () (for a Unicode stream) and
then construct usable objects from the returned stream.
For Clob storage use setClob() from a PreparedStatement or updateObject() from an
updatable ResultSet. This is where most discussions end, with the example basically
retrieving a Clob from one row and putting it to another row in the same or a different
table.
But how does a Clob get populated in the first place? There's a clue in the Clob
getAsciiStream () and getCharacterStream () methods: use Prepared Statements
setAsciiStream() or setCharacterStream() methods to populate the Clob.

JDBC-Overview
Blob
A Blob is a JDBC interface mapping for an SQL BLOB. A Blob is obtained by the
getBlob() methods of a ResultSet or CallableStatement. A Blob has methods to get its
number of bytes and to determine the starting position of another Blob or an array of bytes
in the current Blob. These methods work without materializing the data. To materialize the
data, you can use getBinaryStream () or getBytes () (for part or all of the Blob) and then
construct usable objects from the returned stream or byte array.
For Blob storage use setBlob () from a PreparedStatement or updateObject from an
updatable ResultSet. Again, this is where most discussions end, with the example retrieving
a Blob from one row and putting it to another row in the same or a different table.
How does Blob data get there in the first place? Again, look at the Blob methods, this time
getBinaryStream () and getBytes (): use Prepared Statements setBinaryStream () or
setBytes() methods to populate the Blob.

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.
The passed SQLException object has the following methods available for retrieving
additional information about the exception:
Method
getErrorCode( )
getMessage( )

getSQLState( )
getNextException( )
printStackTrace( )
printStackTrace(PrintStream s)
printStackTrace(PrintWriter w)

Description
Gets the error number associated with the exception.
Gets the JDBC driver's error message for an 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 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 exception chain.
Prints the current exception, or throwable, and its
backtrace to a standard error stream.
Prints this throwable and its backtrace to the print
stream you specify.
Prints this throwable and its backtrace to the print writer
you specify.

JDBC-Overview

New Features
The JDBC 3.0 specification shipped as part of the J2SE 1.4 release early this year. The key
goals of the JDBC Expert Panel were to align with the most important features of SQL99,
to combine all of the previous JDBC specifications into a single document, to provide a
standard way to take advantage of native DBMS functionality, and to improve scalability.
The 3.0 specification contains a collection of useful new features. Although none of these
new features taken alone would be considered major, there are several useful enhancements
in JDBC 3.0 that make it good news for JDBC users.
Transactional Savepoints: One of the more useful new features is transactional
savepoints. Traditionally, database transactions have been all or nothing types of events.
An application would start a transaction, it might insert some rows, do some updates, and
then either make the changes permanent (commit) or discard all of the changes (rollback).
Either all of the changes would be made permanent or none of the changes would be
permanent. With JDBC 3.0, the transactional model is now more flexible. An application
might start a transaction, insert several rows and then create a savepoint. This savepoint
serves as a bookmark. The application might then perform some if/then/else type of logic
such as updating a group of rows. With JDBC 2.0, the application would now have to either
commit all the changes or rollback all the changes. With JDBC 3.0, the application might
conclude that the updates made were a bad idea but the initial inserts were okay. The
application can rollback to the savepoint (the bookmark) and, then, commit the group of
inserts as if the updates have never been attempted (see the code sample).
Statement stmt = conn.createStatement ();
Int rowcount = stmt.executeUpdate (insert into table (event) values (TMM));
Int rowcount = stmt.executeUpdate (insert into costs (cost) values (45.0));
Savepoint sv1 = conn.setSavePoint (svpoint1); // create save point for inserts
Int rowcount = stmt.executeUpdate (delete from employees); // uh-oh
Conn.rollback (sv1); // discard the delete statement but keep the inserts
Conn.commit; // inserts are now permanent

Pooling Enhancements: Connection pooling was present in the JDBC 2.0 specification,
but JDBC 3.0 provides a much finer granularity of control over the connection objects in
the pool. The single most expensive operation in a database application is establishing a
connection. With some databases, establishing a database connection can take up to nine
network roundtrips between the JDBC driver and the database. Connection pooling
essentially involves keeping a cache of database connection objects open and available for
immediate use for any application that wishes to connect. Instead of performing expensive
network round trips to the database server, a connection attempt results in the reassignment of a connection from the local cache to the application. When the application

JDBC-Overview
disconnects, the physical tie to the database server is not severed, but instead, the
connection is placed back into the cache for immediate re-use.
With JDBC 2.0 connection pooling, there were no tuning capabilities. Either you used
connection pooling or you didnt. With 3.0, there is access to a finer level of granularity
available to control the characteristics of the connection pool. For example, whats the
minimum number of connections to keep in the pool, whats the maximum number of
connections to have in the pool, whats the initial pool size, how long can connections
remain idle before they are discarded from the pool, and how often should the connection
pool be evaluated to see if it meets the configuration criteria? These options allow
environments to be tuned for maximum performance and scalability.
In addition to connection pooling tuning options, JDBC 3.0 also specifies semantics for
providing a statement pool. Similar to connection pooling, a statement pool caches away
PreparedStatement objects so that they can be re-used from a cache without application
intervention. For example, an application might create a PreparedStatement object similar
to the following SQL statement: select name, address, dept, salary from personnel where
empid = ? or name like ? or address = ?. When the preparedStatement object is created,
the SQL query is parsed for syntactic validation, checked for semantic validation, and a
query optimization plan is produced. The process of creating a PreparedStatement is
extremely expensive in terms of performance with some database systems such as DB2.
Once the PreparedStatement is closed, a JDBC 3.0 compliant driver will place the
PreparedStatement into a local cache instead of discarding it. If the application later
attempts to create a PreparedStatement with the same SQL query, which is the case in many
applications, then the driver can simply retrieve the associated statement from the local
cache instead of performing a network roundtrip to the server and an expensive database
validation.
One of the good things about both the connection pooling tuning properties and statement
pooling is that their advantages can be realized in existing applications without recoding.
Upgrading an existing environment to include a JDBC 3.0 compliant application server
and/or a JDBC 3.0 compliant driver can improve performance and scalability of already
deployed systems because the JDBC pooling enhancements are not directly invoked by the
application components. Instead, the pooling features are transparently used by the JDBC
infrastructure.
Retrieval of Auto Generated Keys: Many databases have hidden columns (called pseudo
columns) that represent a unique key over every row in a table. For example, Oracle and
Informix have ROWID pseudo columns and Microsoft SQL Server provides identity
columns. Using these types of columns in a query typically provides the absolute fastest
way to access a row since the pseudo columns usually represent the physical disk address
of the data. Prior to JDBC 3.0, an application could only retrieve the value of the pseudo
columns by executing a SELECT statement immediately after inserting the data.

JDBC-Overview
For example:
Using this methodology to retrieve the pseudo columns had two major flaws. The first
problem is that retrieving the pseudo column required a separate query be sent over the
network and executed on the server. The second problem is that because there might not be
a primary key over the table, the search condition of the query might not be able to
uniquely identify the row. In which case, multiple pseudo column values could be returned
and the application is at a loss to figure out which one was actually the value for the most
recently inserted row.
An optional feature of the JDBC 3.0 specification is the ability to retrieve auto generated
key information for a row when the row is inserted into a table. This new functionality
removes both of the drawbacks in existing implementations because a separate query is not
required to retrieve the key and the application is not responsible for the logic to retrieve
the key. For example:
Int rowcount = stmt.executeUpdate (
insert into LocalGeniusList (name) values (Karen)); // insert row
// now get the disk address rowid for the newly inserted row ResultSet rs =
stmt.executeQuery ( select rowid from LocalGeniusList where name = Karen);

Using this methodology to retrieve the pseudo columns had two major flaws. The first
problem is that retrieving the pseudo column required a separate query be sent over the
network and executed on the server. The second problem is that because there might not be
a primary key over the table, the search condition of the query might not be able to
uniquely identify the row. In which case, multiple pseudo column values could be returned
and the application is at a loss to figure out which one was actually the value for the most
recently inserted row.
An optional feature of the JDBC 3.0 specification is the ability to retrieve auto generated
key information for a row when the row is inserted into a table. This new functionality
removes both of the drawbacks in existing implementations because a separate query is not
required to retrieve the key and the application is not responsible for the logic to retrieve
the key. For example:
Int rowcount = stmt.executeUpdate (
insert into LocalGeniusList (name) values (Karen),
Statement.RETURN_GENERATED_KEYS); // insert row AND return key
ResultSet rs = stmt.getGeneratedKeys (); // key is automatically available

JDBC-Overview
Now, the application contains a value that can be used in a search condition to provide the
fastest access to the row and a value that uniquely identifies the row, even when no primary
key exists on the table.
Some databases, like DB2, do not provide an auto generated key such as a pseudo column.
Fortunately, the JDBC 3.0 specification also allows the application to ask for the columns it
knows represent a key on the table.
For example:
The ability to retrieve auto generated keys provides flexibility to the JDBC programmer
and it provides a mechanism to realize performance boosts when accessing data.
Updating BLOB and CLOB Data Types: The SQL99 specification introduced two new
advanced built-in data types, BLOB and CLOB, that provide flexible and fast access to
long binary and character data items. While JDBC 2.0 provided mechanisms to read BLOB
and CLOB data, it lacked an update capability for those types. The lack of a standard
update mechanism resulted in several problems for JDBC application programmers.
The first problem was that some JDBC driver vendors introduced proprietary update
mechanisms for BLOB and CLOB data types. Using proprietary methods inside an API
standard makes those applications non-standard by definition. The second problem is that
many JDBC application developers assumed that they could use existing JDBC methods
such as setString to update the values. Again, this resulted in different behavior on a driverby-driver case and was ultimately non-standard.
JDBC 3.0 introduces a standard mechanism for updating BLOB and CLOB data. Its
important to note that the Blob and Clob interfaces that are available in JDBC only apply to
database systems that support the new SQL99 BLOB and CLOB types. Oracle, DB2, and
Informix are database systems that do support BLOB and CLOB data types. Microsoft
SQL Server and Sybase support Long Varbinary and Long Varchar data types (image and
text) that are somewhat similar to the new SQL99 types, but they do not support BLOB and
CLOB types. Many JDBC application developers mistakenly think that the Blob and Clob
interfaces should be used for all types of long data; however, those interfaces should only
be used with BLOB and CLOB data. The JDBC specification provides methods such as
setString to deal with Long Varchar and Long Varbinary data.

JDBC-Overview
Lets examine how to update the contents of a CLOB column:
// Retrieve the case history for incident 71164 Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery ( select CaseHistory from Cases where
IncidentID=71164);
rs.next(); // position to the row Blob data = rs.getClob (1); // populate our Blob object with
the data Rs.close();
// now lets insert this history into another table stmt.setClob (1, data); // data is the Clob
object we retrieved from the history table
int InsertCount = stmt.executeUpdate (
insert into EscalatedIncidents (IncidentID, CaseHistory, Owner) + Values (71164, ?,
Goodson) );

Multiple Open Result Set Objects: Data architects routinely build much of their business
integrity rules into database system stored procedures. For example, instead of relying on
programmers to independently know all of the tables that need to be updated when
someone new starts in the company, its fairly common that there will be a central stored
procedure, perhaps called AddNewEmployee, which can be called when a new employee is
hired. Calling stored procedures can result in table updates and, also, queries being
executed that return result sets.
Invoking a single stored procedure might result in several result sets being returned to the
calling application. For example, a stored procedure called employeeInfo might return
result sets containing the employees address and personal information, another with a list
of the employees staff if they manage people, and another with a list of all the projects that
the employee is working on.
With JDBC 2.0, an application calling the employeeInfo stored procedure would have to
serially process the three independent result sets that were generated at execution time. If
the application wanted to first report on the projects list, that is the third of the sequenced
result sets, then it would first have to retrieve and discard the first two result sets. This
processing methodology is somewhat inflexible and certainly involves programming
overhead and complexity. It also doesnt allow simultaneous access to any of the result sets
generated from calling a procedure and that restriction limits the flexibility of a JDBC
programmer.

JDBC-Overview
JDBC 3.0 gives the programmer the flexibility to decide if they want concurrent access to
result sets generated from procedures or if they want the resources to be closed when a new
result set is retrieved (JDBC 2.0 compliant behavior). Lets show an example that
simultaneously processes results from the employeeInfo procedure.

// get ready to call the employeeInfo procedure


CallableStatement cstmt = conn.prepareCall ({call employeeInfo (?)});
Cstmt.setInt (1,71164); // bind parameter info for employee with id 71164
Boolean RetCode = Cstmt.execute (); // call the procedure
// For readability well bypass logic for the procedure possibly returning update counts
// first result set will be discarded materialize it and immediately move to the
secondResultSet DiscardRS = cstmt.getResultSet(); // materialize first result set
ResultSet EmpListRS = cstmt.getMoreResults (); // by default, close DiscardRS // the 2nd
result set which is the employees that report to 71164 is now available
ResultSet ProjectsRS = cstmt.getMoreResults (KEEP_CURRENT_RESULT); // the 3rd
result set is now materialized and we can simultaneously operate on both // the employee
list and the project list

Miscellaneous Features: Weve detailed several new JDBC 3.0 features that range from
performance enhancements to programmer flexibility. There are other JDBC 3.0
enhancements including the ability to retrieve parameter metadata (allows programmer
flexibility), allowing stored procedure parameters to be called by name (simplifies
programming), the ability to specify holdable cursors (performance), and more SQL99
advanced data type alignment. Theres something in JDBC 3.0 that will make all JDBC
programmers a little happier and its available now! Remember that inside JDBC, there are
required features and optional features. Before assuming that a feature is supported in your
favorite 3.0 compliant driver, check the database metadata to make sure optional features
are supported.

Vous aimerez peut-être aussi