Introduction


JDBC is a set of classes and interfaces written in Java that allows Java programs to access a database. IBM has several types of JDBC drivers, this how-to is refering to IBM's DB2 type 4 thin driver.

Download driver package


At the time of testing, I got a package called db2_jdbc_t4_fp13.zip from www.ibm.com. We can verify the content of the file:

jar -tf db2_jdbc_t4_fp13.zip
fm@susie:~> /usr/java/jdk1.5.0_09/bin/jar tf db2_jdbc_t4_fp13.zip
db2_jdbc_t4_fp13/
db2_jdbc_t4_fp13/db2jcc.jar
db2_jdbc_t4_fp13/db2jcc_javax.jar
db2_jdbc_t4_fp13/db2jcc_license_cu.jar
db2_jdbc_t4_fp13/sqlj.zip

Install the driver package


In order to work with the driver, Java must be able to find it when called. We can achieve this by adding the drivers zip file location to the Java classpath, or by simply placing the driver file into the Java standard directory for extensions, for JAVA JRE this is the $JAVA_HOME/jre/lib/ext (i.e. /usr/lib64/jvm/jre-1.6.0-ibm/lib/ext) directory. We need to copy the extracted db2_jdbc_t4_fp13/db2jcc.jar and db2_jdbc_t4_fp13/db2jcc_license_cu.jar.

Use the driver to access DB2 through Java


The following example code JdbcTestDB2.java can be used to quickly access and test the JDBC connection.

vi JdbcTestDB2.java
//JdbcTestDB2.java
import java.sql.Connection ;
import java.sql.DriverManager ;
import java.sql.ResultSet ;
import java.sql.Statement ;
import java.sql.SQLException;

class JdbcTestDB2 {
  public static void main (String args[]) {
      try {
        // use the JDBCtype 4 driver
        Class.forName("com.ibm.db2.jcc.DB2Driver");
      }
      catch (ClassNotFoundException e) {
            System.err.println (e) ;
            System.exit (-1) ;
      }
      try {
         Connection connection = DriverManager.getConnection(
         // open connection to database
         // "jdbc:db2://destinationhost:port/dbname", "dbuser", "dbpassword"
         // the DB2 internal data catalog is in a database called "toolsdb"
         "jdbc:db2://localhost:50002/SAMPLE", "db2inst1", "password1");

          // build query, use table "ENV_INST_INFO" in schema "SYSIBM"
          String query = "select INST_NAME from SYSIBMADM.ENV_INST_INFO" ;

          // execute query
          Statement statement = connection.createStatement () ;
          ResultSet rs = statement.executeQuery (query) ;

          // return query result
          while ( rs.next () )
              System.out.println ("DB2 Query result: " + rs.getString (1)) ;
          connection.close () ;
      }
      catch (java.sql.SQLException e) {
          System.err.println (e) ;
          System.exit (-1) ;
        }
    }
}

Compile and run the test program


fm@susie:~> javac JdbcTestDB2.java 
fm@susie:~> java JdbcTestDB2
DB2 Query result: db2inst1

Should this test fail, typical reasons are: