DB2 Version 9.7 for Linux, UNIX, and Windows

簡単な JDBC アプリケーションの例

この簡単な JDBC アプリケーションでは、JDBC アプリケーションに含める必要がある基本要素を示しています。

図 1. 簡単な JDBC アプリケーション
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.");
      System.exit(1);
    }
    url = urlPrefix + args[0];
    user = args[1];
    password = args[2];
    try 
    {                                                                        
      // 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
      con.setAutoCommit(false);
      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
      rs.close();
      System.out.println("**** Closed JDBC ResultSet");
      
      // Close the Statement
      stmt.close();
      System.out.println("**** Closed JDBC Statement");

      // Connection must be on a unit-of-work boundary to allow close
      con.commit();
      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);
      e.printStackTrace();
    }

    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.printStackTrace();
        ex = ex.getNextException(); // For drivers that support chained exceptions
      }
    }
  }  // End main
}    // End EzJava

図 1 の注:

説明
1 このステートメントにより、JDBC コア API が含まれている java.sql パッケージがインポートされます。 アクセスが必要になる可能性のある他の Java™ パッケージについては、『JDBC サポート用の Java パッケージ』を参照してください。
2 String 変数 empNo により、ホスト変数の機能が実行されます。 つまり、この変数は SQL 照会から検索されたデータを保持するために使用されます。 詳細については、『JDBC アプリケーションでの変数』を参照してください。
3a および 3b これら 2 つのステートメントのセットでは、使用可能な 2 つのインターフェースのいずれかを使用して、データ・ソースに接続する方法が示されています。 詳細については、『JDBC アプリケーションによるデータ・ソースへの接続の方法』を参照してください。

ステップ 3a (JDBC ドライバーのロード) は、JDBC 4.0 以降を使用する場合は不要です。

4a および 4b これら 2 つのステートメントのセットでは、JDBC で SELECT を実行する方法が示されています。 他の SQL 操作を実行する方法については、『SQL を実行するための JDBC インターフェース』を参照してください。
5 この try/catch ブロックでは、SQL エラー処理用の SQLException クラスの使用が示されています。 SQL エラーの処理の詳細については、『IBM® Data Server Driver for JDBC and SQLJ 使用時の SQLException の処理』を参照してください。 SQL 警告の処理については、『IBM Data Server Driver for JDBC and SQLJ 使用時の SQLWarning の処理』を参照してください。
6 このステートメントにより、アプリケーションがデータ・ソースから切断されます。 『JDBC アプリケーションでのデータ・ソースからの切断』を参照してください。