IBM Books

Application Development Guide


JDBC Programming

Whether you're writing an application or applet, you typically do the following:

  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 Sun's JDBC specification) and using the db2 subprotocol. For applets, you must also provide the userid, password, host name, and the port number for the applet server; for applications, the DB2 client provides the required 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 username and password.

    getConnection(String url, String userid, String password)
    Establish a connection to the database specified by url with the values for username 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 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.

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 standard extension API. For information on the JDBC specification, see the DB2 Universal Database Java website .

The JDBC 2.0 driver is currently available only on Windows 32-bit operating systems. Before you can use the JDBC 2.0 driver, you must follow the instructions in Performing the Installation.

Features

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. Here is a list of main features that the DB2 JDBC 2.0 driver supports:

Here is a list of features that the DB2 JDBC 2.0 driver does NOT support:

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, we recommend that you modify the application to comply with the new specification.

However, this solution may not be practical for every situation. As a workaround we provide a keyword, JDBCVERSION, that you can set 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 pass it in 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.

Performing the Installation

As the JDBC 2.0 driver is not available for every platform, the JDBC 1.22 driver is still the default driver. To take advantage of the new features of JDBC 2.0, you must install both the JDBC 2.0 driver and JDK 1.2 support for your platform.

To install the JDBC 2.0 driver, enter the usejdbc2 command from the sqllib\java12 directory. This command performs the following tasks:

To switch back to the JDBC 1.22 driver, execute the usejdbc1 batch file from the sqllib\java12 directory.


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]

[ DB2 List of Books | Search the DB2 Books ]