Application Development Guide


JDBC Programming

Both applications and applets typically perform the following tasks:

  1. Import the appropriate Java packages and classes (java.sql.*)
  2. Load the appropriate JDBC driver (COM.ibm.db2.jdbc.app.DB2Driver for applications; COM.ibm.db2.jdbc.net.DB2Driver for applets)
  3. Connect to the database, specifying the location with a URL as defined in the JDBC specification and using the db2 subprotocol. Applets require you to provide the user ID, password, host name, and the port number for the applet server. Applications implicitly use the default value for user ID and password from the DB2 client catalog, unless you explicitly specify alternate values.
  4. Pass SQL statements to the database
  5. Receive the results
  6. Close the connection

After coding your program, compile it as you would any other Java program. You don't need to perform any special precompile or bind steps.

How the DB2Appl Program Works

The following sample program, DB2Appl.java , demonstrates how to code a JDBC program for DB2.

  1. Import the JDBC package. Every JDBC and SQLJ program must import the JDBC package.
  2. Declare a Connection object. The Connection object establishes and manages the database connection.
  3. Set database URL variable. The DB2 application driver accepts URLs that take the form of jdbc:db2:>database-name<.
  4. Connect to database. The DriverManager.getConnection() method is most often used with the following parameters:

    getConnection(String url)
    Establish a connection to the database specified by url with the default user ID and password.

    getConnection(String url, String userid, String password)
    Establish a connection to the database specified by url with the values for user ID and password specified by userid and passwd respectively.
  5. Create a Statement object. Statement objects send SQL statements to the database.
  6. Execute an SQL SELECT statement. Use the executeQuery() method for SQL statements, like SELECT statements, that return a single result set. Assign the result to a ResultSet object.
  7. Retrieve rows from the ResultSet. The ResultSet object allows you to treat a result set like a cursor in host language embedded SQL. The ResultSet.next() method moves the cursor to the next row and returns a boolean false if the final row of the result set has been reached. Restrictions on result set processing depend on the level of the JDBC API that is enabled through the database manager configuration parameters.
  8. Return the value of a column. The ResultSet.getString(n) returns the value of the nth column as a String object.
  9. Execute an SQL UPDATE statement. Use the executeUpdate() method for SQL UPDATE statements. The method returns the number of rows updated as an int value.

JDBC Example: DB2Appl.java

import java.sql.*; (1) 
 
class DB2Appl {
 
   static {
      try {
         Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
      } catch (Exception e) {
         System.out.println(e);
      }
   }
 
   public static void main(String argv[]) {
      Connection con = null; (2)
 
      // URL is jdbc:db2:dbname
      String url = "jdbc:db2:sample"; (3)
 
      try {
         if (argv.length == 0) {
            // connect with default id/password
            con = DriverManager.getConnection(url);
            }
         else if (argv.length == 2) {
            String userid = argv[0];
            String passwd = argv[1];
 
            // connect with user-provided username and password
            con = DriverManager.getConnection(url, userid, passwd); (4)
            }
         else {
            System.out.println("Usage: java DB2Appl [username password]");
            System.exit(0);
         }
 
         // retrieve data from the database
         System.out.println("Retrieve some data from the database...");
         Statement stmt = con.createStatement(); (5)
         ResultSet rs = stmt.executeQuery("SELECT * from employee"); (6)
 
         System.out.println("Received results:");
 
         // display the result set
         // rs.next() returns false when there are no more rows
         while (rs.next()) { (7)
            String a = rs.getString(1); (8)
            String str = rs.getString(2);
 
            System.out.print(" empno= " + a);
            System.out.print(" firstname= " + str);
            System.out.print("");
         }
 
         rs.close();
         stmt.close();
 
         // update the database
         System.out.println("Update the database... ");
         stmt = con.createStatement();
         int rowsUpdated = stmt.executeUpdate("UPDATE employee 
	        SET firstnme = 'SHILI' where empno = '000010'");(9)
 
         System.out.print("Changed "+rowsUpdated);
 
         if (1 == rowsUpdated)
            System.out.println(" row.");
         else
            System.out.println(" rows.");
 
         stmt.close();
         con.close();
      } catch( Exception e ) {
         System.out.println(e);
      }
   }
}

Distributing a JDBC Application

Distribute your JDBC application as you would any other Java application. As the application uses the DB2 client to communicate with the DB2 server, you have no special security concerns; authority verification is performed by the DB2 client.

To run your application on a client machine, you must install on that machine:

To build your application, you must also install the JDK for your operating system. For information on setting up your Java environment, building DB2 Java applications, and running DB2 Java applications, refer to the Application Building Guide.

Distributing and Running a JDBC Applet

Like other Java applets, you distribute your JDBC applet over the network (intranet or Internet). Typically you would embed the applet in a hypertext markup language (HTML) page. For example, to call the sample applet DB2Applt.java, (provided in sqllib/samples/java) you might use the following <APPLET> tag:

   <applet code="DB2Applt.class" width=325 height=275 archive="db2java.zip">
      <param name="server" value="webhost">
      <param name="port" value="6789">
   </applet>

To run your applet, you need only a Java-enabled Web browser on the client machine. When you load your HTML page, the applet tag instructs your browser to download the Java applet and the db2java.zip class library, which includes the DB2 JDBC driver implemented by the COM.ibm.db2.jdbc.net class. When your applet calls the JDBC API to connect to DB2, the JDBC driver establishes separate communications with the DB2 database through the JDBC applet server running on the Web server.
Note:To ensure that the Web browser downloads db2java.zip from the server, ensure that the CLASSPATH environment variable on the client does not include db2java.zip. Your applet may not function correctly if the client uses a local version of db2java.zip.

For information on building and distributing Java applets, refer to the Application Building Guide.

JDBC 2.0

JDBC 2.0 is the latest version of JDBC from Sun. This version of JDBC has two defined parts: the core API, and the Optional Package API. For information on the JDBC specification, see the DB2 Universal Database Java Web site .

For information on installing the JDBC 2.0 drivers for your operating system, refer to the Application Building Guide.

JDBC 2.0 Core API Support

The DB2 JDBC 2.0 driver supports the JDBC 2.0 core API, however, it does not support all of the features defined in the specification. The DB2 JDBC 2.0 driver supports the following features of the JDBC 2.0 core API:

Note:DB2 does not support the use of java.sql.Blob or java.sql.Clob in stored procedures, UDFs, or methods.

The DB2 JDBC 2.0 driver does not support the following features:

JDBC 2.0 Optional Package API Support

The DB2 JDBC 2.0 driver supports the following features of the JDBC 2.0 Optional Package API:

Java Naming and Directory Interface (JNDI) for Naming Databases

DB2 provides the following support for the Javing Naming and Directory Interface (JNDI) for naming databases:

javax.naming.Context
This interface is implemented by COM.ibm.db2.jndi.DB2Context, which handles the storage and retrieval of DataSource objects. In order to support persistent associations of logical data source names to physical database information, such as database names, these associations are saved in a file named .db2.jndi. For an application, the file resides (or is created if none exists) in the directory specified by the USER.HOME environment variable. For an applet, you must create this file in the root directory of the web server to facilitate the lookup() operation. Applets do not support the bind(), rebind(), unbind() and rename() methods of this class. Only applications can bind DataSource objects to JNDI.

javax.sql.Datasource
This interface is implemented by COM.ibm.db2.jdbc.DB2DataSource. You can save an object of this class in any implementation of javax.naming.Context. This class also makes use of connection pooling support.

javax.naming.InitialContextFactory
This interface is implemented by COM.ibm.db2.jndi.DB2InitialContextFactory, which creates an instance of DB2Context. Applications automatically set the value of the JAVA.NAMING.FACTORY.INITIAL environment variable to COM.ibm.db2.jndi.DB2InitialContextFactory To use this class in an applet, call InitialContext() using the following syntax:
  Hashtable env = new Hashtable( 5 );
  env.put( "java.naming.factory.initial",
           "COM.ibm.db2.jndi.DB2InitialContextFactory" );
  Context ctx = new InitialContext( env );

Connection Pooling

DB2ConnectionPoolDataSource and DB2PooledConnection provide the hooks necessary for you to implement your own connection pooling module, as follows:

javax.sql.ConnectionPoolDataSource
This interface is implemented by COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource, and is a factory of COM.ibm.db2.jdbc.DB2PooledConnection objects.

javax.sql.PooledConnection
This interface is implemented by COM.ibm.db2.jdbc.DB2PooledConnection.

Java Transaction APIs (JTA)

DB2 supports the Java Transaction APIs (JTA) through the DB2 JDBC application driver. DB2 does not provide JTA support with the DB2 JDBC net driver.

javax.sql.XAConnection
This interface is implemented by COM.ibm.db2.jdbc.DB2XAConnection.

javax.sql.XADataSource
This interface is implemented by COM.ibm.db2.jdbc.DB2XADataSource, and is a factory of COM.ibm.db2.jdbc.DB2PooledConnection objects.

javax.transactions.xa.XAResource
This interface is implemented by COM.ibm.db2.jdbc.app.DBXAResource.

javax.transactions.xa.Xid
This interface is implemented by COM.ibm.db2.jdbc.DB2Xid.

JDBC 2.0 Compatibility

This version of the specification is backward compatible with the previous version (1.22). However, the DB2 JDBC 1.22 driver supports LOB types as an extension of the JDBC 1.22 specification, and this extension is not part of the new specification's backward compatibility. This means that existing JDBC applications that rely on the LOB support of the JDBC 1.22 driver may not work with the new driver. For information on the DB2 JDBC 1.22 driver support for LOBs and graphic types, see Using LOBs and Graphical Objects With JDBC 1.22. To fix the problem, consider modifying the application to take advantage of the LOB support offered by the JDBC 2.0 driver.
Note:You cannot use the DB2 JDBC 2.0 driver support for LOB and graphic types in stored procedures or UDFs. To use LOB or graphic types in stored procedures or UDFs, you must use the JDBC 1.22 driver support.

However, this solution may not be practical for every situation. As a workaround, you can set the keyword JDBCVERSION to "122" to tell the JDBC 2.0 driver to use the 1.22 version of LOB support. The default is "200" to tell the JDBC 2.0 driver to use the 2.0 version of LOB support. You can set this keyword in db2cli.ini, or as a connection attribute in the getConnection property argument.
Note:If you use the JDBC 1.22 driver, the JDBCVERSION keyword does not affect LOB support for JDBC.


[ Top of Page | Previous Page | Next Page ]