Sie sind auf Seite 1von 19

JDBC driver

From Wikipedia, the free encyclopedia

Jump to: navigation, search


This article may contain original research. Please improve it by verifying the
claims made and adding references. Statements consisting only of original
research may be removed. More details may be available on the talk page.
(September 2007)

A JDBC driver is a software component enabling a Java application to interact with a


database.[1]

To connect with individual databases, JDBC (the Java Database Connectivity API)
requires drivers for each database. The JDBC driver gives out the connection to the
database and implements the protocol for transferring the query and result between client
and database.

Contents
[hide]

• 1 JDBC Architecture
o 1.1 Type 1 Driver - JDBC-ODBC bridge
 1.1.1 Functions
 1.1.2 Advantages
 1.1.3 Disadvantages
o 1.2 Type 2 Driver - Native-API Driver specification
 1.2.1 Advantages
 1.2.2 Disadvantages
o 1.3 Type 3 Driver - Network-Protocol Driver
 1.3.1 Functions
 1.3.2 Advantages
 1.3.3 Disadvantages
o 1.4 Type 4 Driver - Native-Protocol Driver
 1.4.1 Functions
 1.4.2 Advantages
 1.4.3 Disadvantage
o 1.5 List of JDBC Drivers
o 1.6 See also

o 1.7 References
[edit] JDBC Architecture
The JDBC API contains two major sets of interfaces:

• JDBC API for application writers


• JDBC driver low-level API for driver writers

JDBC technology drivers fit into one of four categories. [2]

[edit] Type 1 Driver - JDBC-ODBC bridge

Schematic of the JDBC-ODBC bridge

The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver
implementation that employs the ODBC driver to connect to the database. The driver
converts JDBC method calls into ODBC function calls.

The driver is platform-dependent as it makes use of ODBC which in turn depends on


native libraries of the underlying operating system the JVM is running upon. Also, use of
this driver leads to other installation dependencies; for example, ODBC must be installed
on the computer having the driver and the database must support an ODBC driver. The
use of this driver is discouraged if the alternative of a pure-Java driver is available. The
other implication is that any application using a type 1 driver is non-portable given the
binding between the driver and platform.

[edit] Functions

• Translates query obtained by JDBC into corresponding ODBC query, which is


then handled by the ODBC driver.
• Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This
driver is native code and not Java, and is closed source.
• Client -> JDBC Driver -> ODBC Driver -> Database
• There is some overhead associated with the translation work to go from JDBC to
ODBC.

[edit] Advantages

• Almost any database for which ODBC driver is installed, can be accessed.
• A type 1 driver is easy to install.

[edit] Disadvantages

• Performance overhead since the calls have to go through the JDBC overhead
bridge to the ODBC driver, then to the native db connectivity interface.
• The ODBC driver needs to be installed on the client machine.
• Considering the client-side software needed, this might not be suitable for applets.
• Will not be suitable for Java applets.

[edit] Type 2 Driver - Native-API Driver specification


Schematic of the Native API driver

The JDBC type 2 driver, also known as the Native-API driver, is a database driver
implementation that uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API.

The type 2 driver is not written entirely in Java as it interfaces with non-Java code that
makes the final database calls. The driver is compiled for use with the particular
operating system. For platform interoperability, the Type 4 driver, being a full-Java
implementation, is preferred over this driver.

However the type 2 driver provides more functionality and better performance than the
type 1 driver as it does not have the overhead of the additional ODBC function calls.

[edit] Advantages

• Better performance than Type 1 Driver (JDBC-ODBC bridge).

better performance than the type 1 driver as it does not have the overhead of the
additional ODBC function calls.

[edit] Disadvantages

• The vendor client library needs to be installed on the client machine.


• Cannot be used in web-based application due the client side software needed.
• Not all databases have a client side library
• This driver is platform dependent

[edit] Type 3 Driver - Network-Protocol Driver

Schematic of the Network Protocol driver

The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is
a database driver implementation which makes use of a middle tier between the calling
program and the database. The middle-tier (application server) converts JDBC calls
directly or indirectly into the vendor-specific database protocol.

This differs from the type 4 driver in that the protocol conversion logic resides not at the
client, but in the middle-tier. Like type 4 drivers, the type 3 driver is written entirely in
Java. The same driver can be used for multiple databases. It depends on the number of
databases the middleware has been configured to support. The type 3 driver is platform-
independent as the platform-related differences are taken care by the middleware. Also,
making use of the middleware provides additional advantages of security and firewall
access.
[edit] Functions

• Follows a three tier communication approach.


• Can interface to multiple databases - Not vendor specific.
• The JDBC Client driver written in java, communicates with a middleware-net-
server using a database independent protocol, and then this net server translates
this request into database commands for that database.
• Thus the client driver to middleware communication is database independent.
• Client -> JDBC Driver -> Middleware-Net Server -> Any Database

[edit] Advantages

• Since the communication between client and the middleware server is database
independent, there is no need for the vendor db library on the client machine. Also
the client to middleware need not be changed for a new database.
• The Middleware Server (which can be a full fledged J2EE Application server) can
provide typical middleware services like caching (connections, query results, and
so on), load balancing, logging, auditing etc.
• Eg. for the above include jdbc driver features in Weblogic.
o Can be used in internet since there is no client side software needed.
o At client side a single driver can handle any database. (It works provided
the middleware supports that database!)

[edit] Disadvantages

• Requires database-specific coding to be done in the middle tier.


• An extra layer added may result in a time-bottleneck. But typically this is
overcome by providing efficient middleware services described above.

[edit] Type 4 Driver - Native-Protocol Driver


Schematic of the Native-Protocol driver

The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a
database driver implementation that converts JDBC calls directly into the vendor-specific
database protocol.

The type 4 driver is written completely in Java and is hence platform independent. It is
installed inside the Java Virtual Machine of the client. It provides better performance
over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into
ODBC or database API calls. Unlike the type 3 drivers, it does not need associated
software to work.

As the database protocol is vendor-specific, separate drivers, usually vendor-supplied,


need to be used to connect to different databases.

[edit] Functions

• Type 4 drivers are entirely written in Java that communicate directly with a
vendor's database, usually through socket connections. No translation or
middleware layers are required, improving performance.
• The driver converts JDBC calls into the vendor-specific database protocol so that
client applications can communicate directly with the database server.
• Completely implemented in Java to achieve platform independence.
• e.g. include the widely used Oracle thin driver - oracle.jdbc.driver.OracleDriver
which connect to jdbc:oracle:thin URL format.
• Client -> Native protocol JDBC Driver -> Database server
[edit] Advantages

• These drivers don't translate the requests into an intermediary format (such as
ODBC), nor do they need a middleware layer to service requests. Thus the
performance may be considerably improved.
• All aspects of the application to database connection can be managed within the
JVM; this can facilitate easier debugging.

[edit] Disadvantage

• At client side, a separate driver is needed for each database.

InitialContext iCtx = new InitialContext();

DataSource ds = (DataSource) iCtx.lookup("DSName");

Connection conn = ds.getConnection();

//In the config.xml file...

<JDBCDataSource JNDIName="DSName" Name="xyz" PoolName="xyz"


Targets="myserver"/>

<JDBCConnectionPool CapacityIncrement="1"

DriverName="oracle.jdbc.driver.OracleDriver" InitialCapacity="3"

LoginDelaySeconds="1" MaxCapacity="10" Name="xyz"

Password="blah blah"

Properties="user=USERNAME;dll=ocijdbc8;protocol=thin"

RefreshMinutes="5" Targets="myserver"

TestConnectionsOnReserve="true" TestTableName="dual"
URL="jdbc:oracle:thin:@database connect string"/>
Skip to Content Sun
Sun.com
About Sun
Downloads
Products
Solutions
Support
Training

Java
Java for your computer
Stay up to date with the latest versions of Java for your desktop computer.
Free and Open Source Java
Get your own copy of the underlying software code for the Java language.
Download the latest JDK
The basic developer kit for Java developers.
Download the Java EE SDK
The SDK supports Java SE 6 and the latest Java EE 5 technologies.
Download NetBeans IDE
Get the award-winning, open-source tool suite for developing Java applications.
Java Developer Resources
Visit java.sun.com for everything you need to know about the Java technology.
Java Developer Tools
See and download all software tools available from Sun.
Java Standard Edition
For developing and deploying Java applications for the desktop, servers, embedded, and
real-time environments.
Java Enterprise Edition
For enterprise, server-side Java applications.
Java Micro Edition
For Java applications running on mobile devices.
Java Training
Sharpen your Java skills with courses from the source.
Java Support
Get dedicated help from Sun including technical assistance, product support, and support
for deployed Java applications.

Solaris
OpenSolaris
Download, develop and collaborate with OpenSolaris
Solaris
Download the most advanced operating system in the world
Sun Studio
Optimizing compilers and tools for C/C++/Fortran application development
Solaris Developer Center
Explore the resources and community available to the Solaris developer.
Sun Developer Services
Get technical assistance, product support, training, and other services from the source.
BigAdmin
A community site with Solaris system administration information, hardware
compatibility, a script library, and other resources for administrators of Sun products.
Communities
OpenJDK
The place to collaborate on the open-source JDK, an implementation of the Java
Platform, Standard Edition specification.
Mobile & Embedded
The Mobile & Embedded Community enables and empowers developers to collaborate
and innovate, driving the evolution and adoption of the Java(TM) Platform, Micro
Edition (Java ME) for mobile and embedded devices.
GlassFish
The GlassFish community is building free, open source, production-quality, enterprise
software.
NetBeans
You have the opportunity to submit bugs and feature requests in IssueZilla, submit news
for the NetBeans Community, and contribute code or even create a project of your own.
Welcome to the team!
OpenSolaris
The OpenSolaris source code is already cutting edge, but innovation happens
everywhere, so we welcome your involvement.
OpenSPARC
OpenSPARC.net is the genesis of a vision to create a larger community where open
conversations and collaborative development projects spawn dramatic innovations around
chip design.
Open Storage
The OpenSolaris storage community is your gateway to data management related
communities and projects - file sharing, file systems, volume managers, data services,
storage drivers, and much more.
OpenJFX
Project OpenJFX is a community for sharing early versions of the JavaFX Script
language and for collaborating on its development.
java.net
A gathering place for Java technology enthusiasts and existing communities across
industries, platforms, and interest groups.
Sun Student Developers
The SDN Academic Developer Program offers you ready access to tools, resources, and
student communities.
Java Community Process
The JCP gives you a chance to both have your own work become an official component
of the Java platform, and to offer suggestions for improving and growing the technology.
My SDN Account
Update My Profile
Join SDN
Join SDN Now
Why Join
Becoming an Sun Developer Network (SDN) member makes you part of a vibrant
worldwide community of developers, and gives you access to cool stuff and exclusive
offers.
Top of Form
utf-8 main-developer-a
» search tips
Bottom of Form

APIs
Java SE
Java EE
Java ME
Solaris
Sun Studio Compilers & Tools
Web Services
Java Card
See All »
Downloads
Early Access
Java SE
Java EE
Java ME
JavaFX
Solaris
NetBeans
Sun Studio Compilers & Tools
MySQL
VirtualBox
See All »
Products
Java SE
Java SE for Business
Java SE for Embedded
Java Real-Time System
Java EE
Java ME
JavaFX
Scripting
Solaris
Sun Studio Compilers & Tools
NetBeans IDE
Open Storage
Mobility
MySQL
Java DB
See All »
Support
Big Admin
Developer Services
Forums
Globalization
See All »
Training
Certification
Developer Training
See All »
Participate
Forums
Blogs
Wikis
Java User Groups
Newsletters
Events
See All »
SDN Home > Products & Technologies > Java Technology > J2EE > JDBC > Learning
> Tutorial and Code Camps > jGuru: JDBC 2.0 Fundamentals >

Tutorials
jGuru: JDBC 2.0 Fundamentals

Print-friendly Version

Short Course

by
[About This Course| Exercises]
Course Outline
Introduction to JDBCTM
SQL
ODBC
The Java Programming Language and JDBC
JDBC 1.0
JDBC 2.0
A Complete Example
Describing the Scenario
Creating a Database
Connecting to the Database
Creating a Table
Inserting Information into a Database
Step by Step
Retrieving Information from a Database
Data Navigation
Data Extraction
Connecting a Java Program to a Database
Areas Controlled by the Connection Interface
Generalizing Connection Information
Statements, ResultSets, and Interacting with a Database
Modifying Data
Database Queries
Prepared Statements
Java-SQL Type Equivalence
JDBC Exception Types and Exception Handling
SQL Exceptions
SQL Warnings
Data Truncation
Sample Error Test Outcomes
Metadata
Database Metadata
ResultSet Metadata
Escape Syntax and Scalar Functions
Stored Procedures
MetaData Support
Parameter INs and OUTs
Escape Syntax
CallableStatement
Setup, Invocation, and Value Retrieval
Transactions
Commit
Rollback
Concurrency
Typical Transaction Code
Batch Update Facility
Typical Batch Update Code
Handling BatchUpdateException
Typical BatchUpdateException Handler
Scrollable Result Sets
Usage Notes
LOBs
Locators
Clob
Blob
SQL Conformance
The JDBC 2.0 Optional Package and J2EE
Using JDBC with JavaServer Pages

Cloudscape Installation and Setup


Starting and Stopping Cloudscape
SQL Primer
Creating Tables
Accessing Columns
Storing Information
Resources
Specific Information
Web Sites
Documentation and Specs
Books
SQL Resources
Web Sites
Books
Introduction to JDBC
JDBC is a Java API (Application Programming Interface) that
documents a standard framework for dealing with tabular and,
generally, relational data. While JDBC 2.0 begins a move to
make SQL semi-transparent to the programmer, SQL is still the
lingua franca of the standard database engines and represents a
major industry victory in the effort to separate data from code.
Before getting into the course proper, it's worth taking a few
moments to provide some background on the movement from
straight-ahead SQL to JDBC.
SQL
SQL is a standardized language used to create, manipulate,
examine, and manage relational databases. This course will not
extensively explain SQL, although a very basic SQL Primer and
SQL Resources are provided.
However, you should understand the following:
A database is essentially a smart container for tables.
A table is a container comprised of rows.
A row is (conceptually) a container comprised of columns.
A column is a single data item having a name, type, and value.
While you should review the definitions and understand the
important differences, initially you can use the following
analogs: A database approximates a file system; a table
approximates a file; a row approximates a record or structure;
and a column approximates a field or variable. If these terms are
unfamiliar, you should review some programming resources,
particularly in the area of Input/Output (I/O) operations, before
proceeding with the course.
Because SQL is an application-specific language, a single
statement can be very expressive and can initiate high-level
actions, such as sorting and merging, on an entire set of data.
SQL was standardized in 1992 so that a program could
communicate with most database systems without having to
change the SQL commands. However, you must connect to a
database before sending SQL commands, and each database
vendor has a different interface to do so, as well as different
extensions of SQL. Enter ODBC.
ODBC
ODBC (Open Database Connectivity), a C-based interface to
SQL-based database engines, provides a consistent interface for
communicating with a database and for accessing database
metadata (information about the database system vendor, how
the data is stored, and so on). Individual vendors provide
specific drivers or "bridges" to their particular database
management system. Consequently, thanks to ODBC and SQL,
you can connect to a database and manipulate it in a standard
way. It is no surprise that, although ODBC began as a PC
standard, it has become nearly an industry standard.
Although SQL is well-suited for manipulating databases, it was
not designed to be a general application language; rather, it was
intended to be used only as a means of communicating with
databases. Another more general and complete programming
language is needed to host and feed SQL statements to a
database and process results for data manipulation, visual
display, or report generation. Unfortunately, you cannot easily
write a program that will run on multiple platforms, even
though the database connectivity standardization issue has been
largely resolved. For example, if you wrote a database client in
C++, you might have to totally rewrite the client for another
platform; that is to say, your PC version would not run on a
Macintosh. There are two reasons for this. First, C++ as a
language is not portable because C++ is not completely
specified (for example, how many bits does an int hold?).
Second, and more importantly, support libraries such as network
access and GUI (Graphical User Interface) frameworks are
different on each platform. Enter the Java programming
language and JDBC.
The Java Programming Language and JDBC
A Java program, written properly and according to
specification, can run on any Java technology-enabled platform
without recompilation. The Java programming language is
completely specified and, by definition, a Java technology-
enabled platform must support a known core of libraries. One
such library is the java.sql package or JDBC, which you can
think of as a portable version of ODBC, and is itself a major
standard. Using the Java programming language in conjunction
with JDBC provides a truly portable solution to writing
database applications.
Note: While portable applications and a standard database
interface are major achievements, keep in mind that, for
historical, competitive, and sometimes nonsensical reasons, the
various databases are not completely standardized. This may
mean that you have to aim for a lowest common denominator in
terms of capabilities or build-in adjustments for specific
databases, even on the same platform. This problem remains
whether you use standard SQL, ODBC, JDBC, or other
solutions.
A JDBC driver is a class that implements the JDBC Driver
interface and understands how to convert program (and
typically SQL) requests for a particular database. Clearly, the
driver is what makes it all work. There are four different driver
types, which are discussed in the JDK (Java Development Kit)
documentation at JDBC Driver Types. This course uses type 4
drivers because of their nearly zero installation requirements
and dynamic nature. Another driver type may make more sense
for your particular project. Most database vendors now provide
drivers to implement the JDBC API for their particular systems.
These are generally provided free of charge. Third party drivers
are also available, ranging in cost from free to very expensive.
For links to JDBC driver resources, see Specific Information
and the other Resources.
JDBC 1.0
The JDBC 1.0 API provided the basic framework for data
access, consisting primarily of the following interfaces and
classes:
Driver
DriverManager
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
DatabaseMetaData
ResultSetMetaData
Types
As you will see in this course, you pass a Driver to the
DriverManager and then obtain a Connection. A Statement,
PreparedStatement, or CallableStatement is then created and
used to update the database or execute a query. A query returns
a ResultSet containing the requested data, which is retrieved by
Type. DatabaseMetaData and ResultSetMetaData classes are
available to provide information about a database or a
ResultSet.
JDBC 2.0
The JDBC 2.0 API is broken into two parts: the core API, which
this course discusses, and the JDBC 2.0 Optional Package. In
general, the JDBC 2.0 core API adds a few more classes, but is
primarily concerned with performance, class enhancements and
functionality, and the new SQL3 (also known as SQL-99)
datatypes.
The new functionality in the core API includes scrollable result
sets, batch updates, programmatic inserts, deletes, and updates,
performance hints, character streams for streams of
internationalized Unicode characters, full precision for
java.math.BigDecimal values and support for time zones in
Date, Time, and Timestamp values.
At the time this course was prepared, the JDBC 3.0 draft was
under review and planned to be included in the 1.4 release of
the JDK.
A Complete Example
The first hands-on experience with JDBC in this course
involves a basic but complete example to illustrate the overall
concepts related to creating and accessing information in a
database. The fundamental issues encountered when writing any
database application are:
Creating a database. A database can be created using tools
supplied by the database vendor, or via SQL statements fed to
the database from a Java program. Since there is normally a
database administrator (of course, as a developer, this may be
you), and not all JDBC drivers support database creation
through Data Definition Language ( DDL), this topic will, in
general, be left as DBMS (DataBase Management System) and
driver specific. If you are interested in more details, there
typically is a CREATE DATABASE statement, but be sure to
review your DBMS SQL reference, as it is not part of the SQL
standard, but is DBMS-dependent.
Connecting to the database. This is the first job of the JDBC
driver, and specific information must be passed
to it. The basic information requirements are a Database URL
(Universal Resource Locator), a User ID, and a Password.
Depending on the driver, there may be many other arguments,
attributes, or properties available. Here are two examples:
Database Connection URL Attributes.
AS/400 JDBC Properties.
Creating a table. While the database contains tables, the tables
are the actual components that contain data, in the form of rows
and columns. Table creation is accomplished by the DDL
CREATE TABLE statement. This statement has many options,
some differing from vendor to vendor; again, be sure to review
your DBMS SQL reference for specifics.
Inserting information into a database. Again, data can be
entered and maintained using database-specific tools, or with
SQL statements sent programmatically. This course, as might be
expected, will focus on using JDBC to send SQL statements to
the database.
Selectively retrieving information. After sending SQL
commands to retrieve the data and using JDBC to get results
into variables, program code works as with any other variables
to display or manipulate that data.
Describing the Scenario
The initial task for this example requires setting up the
structures and inserting data to track java (that is, coffee) intake
at the jGuru Jive Java Jumphouse, better known to the initiated
as the 4J Cafe. Then a report must be generated for 4J Cafe
management that includes total coffee sales and the maximum
coffee consumed by a customer in one day. Here's the data:
Coffee Consumption at the jGuru Jive Java Jumphouse
"At the 4J Cafe, caffeine is our most important product"
Entry Customer DOW Cups Type
1 John Mon 1 JustJoe
2 JS Mon 1 Cappuccino
3 Marie Mon 2 CaffeMocha
4 Anne Tue 8 Cappuccino
5 Holley Tue 2 MoJava
6 jDuke Tue 3 Cappuccino
7 Marie Wed 4 Espresso
8 JS Wed 4 Latte
9 Alex Thu 3 Cappuccino
10 James Thu 1 Cappuccino
11 jDuke Thu 4 JustJoe
About Sun | About This Site | Newsletters | A Sun Developer
Contact Us | Employment Network Site
How to Buy | Licensing | Terms of Use | Privacy Unless otherwise
| Trademarks licensed, code in all
technical manuals h
(including articles, F
samples) is provided
Copyright 1994-2010 Sun Microsystems, Inc. under this License.

Sun Developer R
Feeds
Feedback
Click here to
rate this page

Das könnte Ihnen auch gefallen