Java Database Connectivity
Encyclopedia
Java DataBase Connectivity, commonly referred to as JDBC, is an API
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 for the Java programming language
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

 that defines how a client may access a database
Database
A database is an organized collection of data for one or more purposes, usually in digital form. The data are typically organized to model relevant aspects of reality , in a way that supports processes requiring this information...

. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases
Relational database management system
A relational database management system is a database management system that is based on the relational model as introduced by E. F. Codd. Most popular databases currently in use are based on the relational database model....

. A JDBC-to-ODBC
Open Database Connectivity
In computing, ODBC is a standard C interface for accessing database management systems . The designers of ODBC aimed to make it independent of database systems and operating systems...

 bridge enables connections to any ODBC-accessible data source in the JVM host environment.

History and implementation

Sun Microsystems
Sun Microsystems
Sun Microsystems, Inc. was a company that sold :computers, computer components, :computer software, and :information technology services. Sun was founded on February 24, 1982...

 released JDBC as part of JDK
Java Development Kit
The Java Development Kit is an Oracle Corporation product aimed at Java developers. Since the introduction of Java, it has been by far the most widely used Java SDK. On 17 November 2006, Sun announced that it would be released under the GNU General Public License , thus making it free software...

 1.1 on February 19, 1997.
It has since formed part of the Java Standard Edition
Java Platform, Standard Edition
Java Platform, Standard Edition or Java SE is a widely used platform for programming in the Java language. It is the Java Platform used to deploy portable applications for general use...

.

The JDBC classes are contained in the Java package
Java package
A Java package is a mechanism for organizing Java classes into namespaces similar to the modules of Modula. Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time...

  and .

Starting with version 3.1 , JDBC has been developed under the Java Community Process
Java Community Process
The Java Community Process or JCP, established in 1998, is a formalized process that allows interested parties to get involved in the definition of future versions and features of the Java platform....

. JSR 54 specifies JDBC 3.0 (included in J2SE 1.4), JSR 114 specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0 (included in Java SE 6).

Functionality

JDBC allows multiple implementations to exist and be used by the same application. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections.

JDBC connections support creating and executing statements. These may be update statements such as SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....

's CREATE, INSERT, UPDATE and DELETE, or they may be query statements such as SELECT. Additionally, stored procedures may be invoked through a JDBC connection. JDBC represents statements using one of the following classes:
– the statement is sent to the database server each and every time. – the statement is cached and then the execution path is pre determined on the database server allowing it to be executed multiple times in an efficient manner. – used for executing stored procedures on the database.

Update statements such as INSERT, UPDATE and DELETE return an update count that indicates how many rows were affected in the database. These statements do not return any other information.

Query statements return a JDBC row result set. The row result set is used to walk over the result set. Individual columns in a row are retrieved either by name or by column number. There may be any number of rows in the result set. The row result set has metadata that describes the names of the columns and their types.

There is an extension to the basic JDBC API in the .

JDBC connections are often managed via a connection pool rather than obtained directly from the driver. Examples of connection pools include BoneCP,
C3P0 and DBCP

Examples

The method is used to load the JDBC driver class. The line below causes the JDBC driver from some jdbc vendor to be loaded into the application. (Some JVMs also require the class to be instantiated with .)


Class.forName( "com.somejdbcvendor.TheirJdbcDriver" );


In JDBC 4.0, it's no longer necessary to explicitly load JDBC drivers using Class.forName. See JDBC 4.0 Enhancements in Java SE 6.

When a class is loaded, it creates an instance of itself and registers it with the . This can be done by including the needed code in the driver class's static block. e.g. DriverManager.registerDriver(Driver driver)

Now when a connection is needed, one of the DriverManager.getConnection methods is used to create a JDBC connection.


Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword" );
try {
/* you use the connection here */
} finally {
//It's important to close the connection when you are done with it
try { conn.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}


The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:" protocol, but the rest is up to the particular vendor. Once a connection is established, a statement can be created.


Statement stmt = conn.createStatement;
try {
stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
} finally {
//It's important to close the statement when you are done with it
try { stmt.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}


Note that Connections, Statements, and ResultSets often tie up operating system
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...

 resources such as sockets or file descriptor
File descriptor
In computer programming, a file descriptor is an abstract indicator for accessing a file. The term is generally used in POSIX operating systems...

s. In the case of Connections to remote database servers, further resources are tied up on the server, e.g., cursors for currently open ResultSets.
It is vital to close any JDBC object as soon as it has played its part;
garbage collection should not be relied upon.
Forgetting to close things properly results in spurious errors and misbehaviour.
The above try-finally construct is a recommended code pattern to use with JDBC objects.

Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query.


Statement stmt = conn.createStatement;
try {
ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
try {
while ( rs.next ) {
int numColumns = rs.getMetaData.getColumnCount;
for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
} finally {
try { rs.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}
} finally {
try { stmt.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}


Typically, however, it would be rare for a seasoned Java programmer to code in such a fashion. The usual practice would be to abstract the database logic into an entirely different class and to pass preprocessed strings (perhaps derived themselves from a further abstracted class) containing SQL statements and the connection to the required methods. Abstracting the data model from the application code makes it more likely that changes to the application and data model can be made independently.

An example of a PreparedStatement query, using conn and class from first example.


PreparedStatement ps =
conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j WHERE i.name = ? AND j.num = ?" );
try {
// In the SQL statement being prepared, each question mark is a placeholder
// that must be replaced with a value you provide through a "set" method invocation.
// The following two method calls replace the two placeholders; the first is
// replaced by a string value, and the second by an integer value.
ps.setString(1, "Poor Yorick");
ps.setInt(2, 8008);

// The ResultSet, rs, conveys the result of executing the SQL statement.
// Each time you call rs.next, an internal row pointer, or cursor,
// is advanced to the next row of the result. The cursor initially is
// positioned before the first row.
ResultSet rs = ps.executeQuery;
try {
while ( rs.next ) {
int numColumns = rs.getMetaData.getColumnCount;
for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
} // for
} // while
} finally {
try { rs.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
}
} finally {
try { ps.close; } catch (Throwable ignore) { /* Propagate the original exception
instead of this one that you may want just logged */ }
} // try


If a database operation fails, JDBC raises an . There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.

An example of a database transaction
Database transaction
A transaction comprises a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions...

:

boolean autoCommitDefault = conn.getAutoCommit;
try {
conn.setAutoCommit(false);

/* You execute statements against conn here transactionally */

conn.commit;
} catch (Throwable e) {
try { conn.rollback; } catch (Throwable ignore) {}
throw e;
} finally {
try { conn.setAutoCommit(autoCommitDefault); } catch (Throwable ignore) {}
}


Here are examples of host database types which Java can convert to with a function.
setXXX Methods
Oracle Datatype setXXX
CHAR setString
VARCHAR2 setString
NUMBER setBigDecimal
setBoolean
setByte
setShort
setInt
setLong
setFloat
setDouble
INTEGER setInt
FLOAT setDouble
CLOB setClob
BLOB setBlob
RAW setBytes
LONGRAW setBytes
DATE setDate
setTime
setTimestamp


For an example of a CallableStatement (to call stored procedures in the database), see the .

JDBC drivers

JDBC drivers are client-side adapter
Adapter
An adapter or adaptor is a person that adapts or a device that converts attributes of one device or system to those of an otherwise incompatible device or system.Some adapters may only affect physical attributes:...

s (installed on the client machine, not on the server) that convert requests from Java programs to a protocol that the DBMS can understand.

Types

There are commercial and free drivers available for most relational database servers. These drivers fall into one of the following types:
  • Type 1 that calls native code of the locally available ODBC driver.
  • Type 2 that calls database vendor native library on a client side. This code then talks to database over network.
  • Type 3, the pure-java driver that talks with the server-side middleware that then talks to database.
  • Type 4, the pure-java driver that uses database native protocol.


There is also a type called internal JDBC driver, driver embedded with JRE in Java-enabled SQL databases. It's used for Java stored procedure
Java stored procedure
A Java stored procedure is a procedure that is written in Java instead of 3GL languages like PL/SQL and stored in the Oracle database. They are executed by the JVM. For this, the database memory space is used. It is sometimes wrongly abbreviated as JSP....

s. This does not belong to the above classification, although it would likely be either a type 2 or type 4 driver (depending on whether the database itself is implemented in Java or not). An example of this is the KPRB driver supplied with Oracle RDBMS. "jdbc:default:connection" is a relatively standard way of referring making such a connection (at least Oracle and Apache Derby support it). The distinction here is that the JDBC client is actually running as part of the database being accessed, so access can be made directly rather than through network protocols.

Sources

  • SQLSummit.com publishes list of drivers, including JDBC drivers and vendors
  • Sun Microsystems
    Sun Microsystems
    Sun Microsystems, Inc. was a company that sold :computers, computer components, :computer software, and :information technology services. Sun was founded on February 24, 1982...

     provides a list of some JDBC drivers and vendors
  • Simba Technologies
    Simba Technologies
    Simba Technologies is a supplier of standards-based data access solutions located in Vancouver, British Columbia, Canada. Simba Technologies specializes in connectivity for ODBC, JDBC, OLE DB for OLAP and XML for Analysis...

     ships an SDK for building custom JDBC Drivers for any custom/proprietary relational data source
  • DataDirect Technologies provides a comprehensive suite of fast Type 4 JDBC drivers for all major database
  • IDS Software provides a Type 3 JDBC driver for concurrent access to all major databases. Supported features include resultset caching, SSL encryption, custom data source, dbShield

  • OpenLink Software
    OpenLink Software
    Founded in 1992, OpenLink Software, Inc., is a software company headquartered in Burlington, Massachusetts, USA.The company develops and deploys standards-compliant middleware products that cover:...

     ships JDBC Drivers for a variety of databases, including Bridges to other data access mechanisms (e.g., ODBC, JDBC) which can provide more functionality than the targeted mechanism
  • JDBaccess is a Java persistence library for MySQL
    MySQL
    MySQL officially, but also commonly "My Sequel") is a relational database management system that runs as a server providing multi-user access to a number of databases. It is named after developer Michael Widenius' daughter, My...

     and Oracle
    Oracle database
    The Oracle Database is an object-relational database management system produced and marketed by Oracle Corporation....

     which defines major database access operations in an easy usable API above JDBC
  • JNetDirect provides a suite of fully Sun J2EE certified high performance JDBC drivers.
  • HSQLDB
    HSQLDB
    HSQLDB is a relational database management system written in Java. It has a JDBC driver and supports a large subset of SQL-92 and SQL:2008 standards. It offers a fast, small database engine which offers both in-memory and disk-based tables...

     is a RDBMS
    Relational database management system
    A relational database management system is a database management system that is based on the relational model as introduced by E. F. Codd. Most popular databases currently in use are based on the relational database model....

     with a JDBC driver and is available under a BSD license.
  • SchemaCrawler is an open source API that leverages JDBC, and makes database metadata available as plain old Java objects (POJOs)

External links

Please be aware that this documentation has examples where the JDBC resources are not closed appropriately (swallowing primary exceptions and being able to cause NullPointerExceptions) and has code prone to SQL injection
SQL injection
A SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website in order to dump the database content to the attacker. SQL injection is a code injection technique that exploits a security vulnerability in a website's software...

 API Javadoc
Javadoc
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code.The "doc comments" format used by Javadoc is the de facto industry standard for documenting Java classes. Some IDEs, such as Netbeans and Eclipse automatically generate...

documentation API Javadoc documentation
  • O/R Broker Scala JDBC framework
  • SqlTool Open source, command-line, generic JDBC client utility. Works with any JDBC-supporting database.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK