JDBC 4.0


 

JDBC 4.0

In this section, we will discuss about JDBC 4.0 and it's added new features in Java Platform, Standard Edition (Java SE) 6 .

In this section, we will discuss about JDBC 4.0 and it's added new features in Java Platform, Standard Edition (Java SE) 6 .

JDBC 4.0

In this section, we will discuss about JDBC 4.0 and it's added new features in Java Platform, Standard Edition (Java SE) 6  .

Additions to Java SE 6.0

Java SE version 6 (code name Mustang) ,have added several enhance feature to JDBC API which provide a simpler design and better developer experience. The Java SE 6.0 release mainly aims at providing compatibility, stability, and quality. The Java SE 6.0 have many enhancement particularly in the monitoring and management (JMX), web services, scripting language support (to integrate JavaScript technology with Java source code using the Rhino scripting engine JSR 223), database connectivity, support for annotations, new RowId support to the additional SQLException subclasses and security.

Additions to JDBC 4.0

The main added features in JDBC 4.0 are--

  1.  JDBC driver's class auto-loading
  2. Support for RowId SQL type
  3. DataeSet implementation of SQL using Annotations
  4. Exception handling enhancements
  5. SQL XML support
  6. Support for National Character Set Conversion
  7. Enhanced Support for Large Objects (BLOBs and CLOBs)

In spite of that, the final version of "Jdk 6" have a database based on Apache Derby included in it. This will help developers explore the new JDBC features without having to download, install, and configure a database product separately.

1.JDBC driver's class auto-loading

In JDBC 4.0, we don't need to include 'Class.forName()'in our code, to load JDBC driver. When the method 'getConnection' is called, the 'DriverManager' will automatically load the suitable driver among the JDBC drivers that were loaded at initialization and those loaded explicitly using the same class loader as the current application.

Connection conn = DriverManager.getConnection(Urldatabase,Username,Password);

2.Support for RowId SQL type

In JDBC 4.0,RowID interface is added to support the ROWID data type which is supported by databases such as Oracle and DB2.RowId is useful where in cases where there are multiple records that don't have a unique identifier column and you need to store the query output in a Collection (such Hashtable) that doesn't allow duplicates. We can use ResultSet's "getRowId()" method to get a RowId and PreparedStatement's "setRowId()" method to use the RowId in a query.

The RowId object's value is not portable between data sources and should be considered as specific to the data source when using the set or update methods in PreparedStatement and ResultSet respectively. So, it shouldn't be shared between different Connection and ResultSet objects.

The method getRowIdLifetime() in DatabaseMetaData can be used to determine the lifetime validity of the RowId object. The return value or row id can have one of the values listed below :

RowId value    Description
ROWID_UNSUPPORTED     Doesn't support ROWID data type.
ROWID_VALID_OTHER     Lifetime of the RowID is dependent on database
   vendor implementation.
ROWID_VALID_TRANSACTION    Lifetime of the RowID is within the current transaction
   as long as the row in the database table is not deleted. 
ROWID_VALID_SESSION     Lifetime of the RowID is the duration of the current
   session as long as the row in the database table is not
   deleted.
ROWID_VALID_FOREVER     Lifetime of the RowID is unlimited as long as the row
    in the database table is not deleted.

3.Dataset implementation of SQL using Annotations

An annotation is a declarative programming model where comments, associated with a code element, are used to inject code at runtime. The Annotations allows developers to associate a SQL query with a Java class without writing a lot of code. We can also associate the SQL queries with Java objects specifying query input and output parameters ,by using the Generics and metadata APIs.We don't need to write all the code we usually write to populate the query result into a Java object.

import java.sql.BaseQuery;
import java.sql.DataSet;
import java.sql.Select;
public interface QueryAnnotationExample extends BaseQuery {
@Select(sql="SELECT ID, MODEL, MODEL_YEAR FROM CAR WHERE MODEL_YEAR = ?1")
 public DataSet<Car> getCarsModelYear( String year );
}

4.Exception handling enhancements

Exception handling is an important part of Java programming, especially when connecting to or running a query against a back-end relational database. SQLException is the class that we have been using to indicate database related errors. JDBC 4.0 has several enhancements in SQLException handling. The following are some of the enhancements made in JDBC 4.0 release to provide a better developer's experience when dealing with SQLExceptions:

  1. New SQLException sub-classes
  2. Support for causal relationships
  3. Support for enhanced for-each loop

JDBC 4.0 adds some simple but powerful features to handle exceptions, including support for chained exception and use of the enhanced for-each loop to retrieve such chained exceptions. In the below example, "Example.java" , specifying  "student4"  as a table name that does not exist in the database. It raised a chained exception as follows:

public class Example2 {
  public static void main(String[] args) {
    String dbName = "example";
    String tableName = "student4";
    try {
      con = ds.getConnection();
          stmt = con.createStatement();
      rs = stmt.executeQuery("select * from " + tableName);
    } catch (SQLException sx) {
      for(Throwable e : sx ) {
        System.err.println("Error encountered: " + e);
      }
    }
    finally{
      //close connections 
    }
  }
}

OUTPUT


Error encountered: java.sql.SQLSyntaxErrorException: 
   Table/View 'STUDENT4' does not exist.
Error encountered: java.sql.SQLException: 
   Table/View 'STUDENT4' does not exist.
Exception in thread "main" java.lang.NullPointerException 
   at ex.Examlpe2.main(Examlpe2.java:51)

JDBC 4.0 SQL XML SUPPORT

SQLXML is a mapping in the Java programming language for the XML data type in SQL. XML is a built-in type that stores an XML value as a column value in a row of the target table. By default, drivers implement an SQLXML object as a logical pointer to the XML data rather than the data itself. An SQLXML object is valid for the duration of the transaction in which it was created.

In this example, the following code snippet that read an XML value from a table and parse it into a Document object.

 SQLXML sqlxml = rs.getSQLXML(column);
 InputStream binaryStream = sqlxml.getBinaryStream();
 DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
 Document doc = parser.parse(binaryStream);

It is good to be able to read a column value from underlying table and build a XML document directly

6.Support for National Character Set Conversion

Following is the list of new enhancements made in JDBC classes when handling the National Character Set:

  1. JDBC data types: New JDBC data types, such as NCHAR, NVARCHAR, LONGNVARCHAR, and NCLOB were added.
  2. PreparedStatement: New methods setNString, setNCharacterStream, and setNClob were added.
  3. CallableStatement: New methods getNClob, getNString, and getNCharacterStream were added.
  4. ResultSet: New methods updateNClob, updateNString, and updateNCharacterStream were added to ResultSet interface.

7.Enhanced Support for Large Objects (BLOBs and CLOBs)

The following is the list of enhancements made in JDBC 4.0 for handling the LOBs:

  1. Connection: New methods (createBlob(), createClob(), and createNClob()) were added to create new instances of BLOB, CLOB, and NCLOB objects.
  2. PreparedStatement: New methods setBlob(), setClob(), and setNClob() were added to insert a BLOB object using an InputStream object, and to insert CLOB and NCLOB objects using a Reader object.
  3. LOBs: There is a new method (free()) added in Blob, Clob, and NClob interfaces to release the resources that these objects hold.

 

Ads