Example of a simple JDBC application

A simple JDBC application demonstrates the basic elements that JDBC applications need to include.

Figure 1. Simple JDBC application
import java.sql.*;                                                            1 

public class EzJava 
  public static void main(String[] args) 
    String urlPrefix = "jdbc:db2:";
    String url;
    String user;
    String password;
    String empNo;                                                             2 
    Connection con;
    Statement stmt;
    ResultSet rs;
    System.out.println ("**** Enter class EzJava");
    // Check the that first argument has the correct form for the portion
    // of the URL that follows jdbc:db2:,
    // as described
    // in the Connecting to a data source using the DriverManager 
    // interface with the IBM Data Server Driver for JDBC and SQLJ topic.
    // For example, for IBM Data Server Driver for 
    // JDBC and SQLJ type 2 connectivity, 
    // args[0] might be MVS1DB2M. For 
    // type 4 connectivity, args[0] might
    // be //stlmvs1:10110/MVS1DB2M.

    if (args.length!=3)
      System.err.println ("Invalid value. First argument appended to "+
       "jdbc:db2: must specify a valid URL.");
      System.err.println ("Second argument must be a valid user ID.");
      System.err.println ("Third argument must be the password for the user ID.");
    url = urlPrefix + args[0];
    user = args[1];
    password = args[2];
      // Load the driver
      Class.forName("com.ibm.db2.jcc.DB2Driver");                             3a 
      System.out.println("**** Loaded the JDBC driver");

      // Create the connection using the IBM Data Server Driver for JDBC and SQLJ
      con = DriverManager.getConnection (url, user, password);                3b 
      // Commit changes manually
      System.out.println("**** Created a JDBC connection to the data source");

      // Create the Statement
      stmt = con.createStatement();                                           4a 
      System.out.println("**** Created JDBC Statement object");

      // Execute a query and generate a ResultSet instance
      rs = stmt.executeQuery("SELECT EMPNO FROM EMPLOYEE");                   4b 
      System.out.println("**** Created JDBC ResultSet object");

      // Print all of the employee numbers to standard output device
      while (rs.next()) {
        empNo = rs.getString(1);
        System.out.println("Employee number = " + empNo);
      System.out.println("**** Fetched all rows from JDBC ResultSet");
      // Close the ResultSet
      System.out.println("**** Closed JDBC ResultSet");
      // Close the Statement
      System.out.println("**** Closed JDBC Statement");

      // Connection must be on a unit-of-work boundary to allow close
      System.out.println ( "**** Transaction committed" );
      // Close the connection
      con.close();                                                            6 
      System.out.println("**** Disconnected from data source");

      System.out.println("**** JDBC Exit from class EzJava - no errors");

    catch (ClassNotFoundException e)
      System.err.println("Could not load JDBC driver");
      System.out.println("Exception: " + e);

    catch(SQLException ex)                                                    5  
      System.err.println("SQLException information");
      while(ex!=null) {
        System.err.println ("Error msg: " + ex.getMessage());
        System.err.println ("SQLSTATE: " + ex.getSQLState());
        System.err.println ("Error code: " + ex.getErrorCode());
        ex = ex.getNextException(); // For drivers that support chained exceptions
  }  // End main
}    // End EzJava

Notes to Figure 1:

Note Description
1 This statement imports the java.sql package, which contains the JDBC core API. For information on other Java™ packages that you might need to access, see "Java packages for JDBC support".
2 String variable empNo performs the function of a host variable. That is, it is used to hold data retrieved from an SQL query. See "Variables in JDBC applications" for more information.
3a and 3b These two sets of statements demonstrate how to connect to a data source using one of two available interfaces. See "How JDBC applications connect to a data source" for more details.

Step 3a (loading the JDBC driver) is not necessary if you use JDBC 4.0 or later.

4a and 4b These two sets of statements demonstrate how to perform a SELECT in JDBC. For information on how to perform other SQL operations, see "JDBC interfaces for executing SQL".
5 This try/catch block demonstrates the use of the SQLException class for SQL error handling. For more information on handling SQL errors, see "Handling an SQLException under the IBM® Data Server Driver for JDBC and SQLJ". For information on handling SQL warnings, see "Handling an SQLWarning under the IBM Data Server Driver for JDBC and SQLJ".
6 This statement disconnects the application from the data source. See "Disconnecting from data sources in JDBC applications".