JDBC 4.1

Java SE 7の一部であるJDBC 4.1には、次の機能が導入されています。

JDBCリソースを自動的に閉じるためのtry-with-resources文の使用

try-with-resources文を使用して、SQLExceptionまたはその他の例外がスローされたかどうかに関係なく、java.sql.Connectionjava.sql.Statement、およびjava.sql.ResultSetオブジェクトを自動的に閉じることができます。try-with-resources文は、try文と、宣言された1つ以上のリソース(セミコロンで区切られる)で構成されます。

詳細は、「try-with-resources文」を参照してください。

次の例ではtry-with-resources文を使用して、Statementオブジェクトのstmtを自動的に閉じます。

  public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {

      ResultSet rs = stmt.executeQuery(query);

      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + ", " + supplierID + ", " + price +
                           ", " + sales + ", " + total);
      }
    }
  }

次の文は、1つのリソースstmtを宣言するtry-with-resources文で、このリソースが自動的に閉じられたあと、tryブロックが終了します。

    try (Statement stmt = con.createStatement()) {

      // ...

    }

RowSet 1.1: RowSetFactoryインタフェースおよびRowSetProviderクラスを使用したRowSetの作成

RowSetFactoryのインスタンスを使用して、RowSetオブジェクトを作成できます。次の例ではRowSetFactoryのインスタンスを使用して、JdbcRowSetオブジェクトjdbcRsを作成します。

  public void testJdbcRowSet(String username, String password) throws SQLException {

    RowSetFactory myRowSetFactory = null;
    JdbcRowSet jdbcRs = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {

      myRowSetFactory = RowSetProvider.newFactory();
      jdbcRs = myRowSetFactory.createJdbcRowSet();

      jdbcRs.setUrl("jdbc:myDriver:myAttribute");
      jdbcRs.setUsername(username);
      jdbcRs.setPassword(password);

      jdbcRs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
      jdbcRs.execute();

      // ...

次の文では、RowSetProviderオブジェクトmyRowSetFactoryを作成し、デフォルトのRowSetFactory実装com.sun.rowset.RowSetFactoryImplを使用します。

      myRowSetFactory = RowSetProvider.newFactory();

あるいは、JDBCドライバに独自のRowSetFactory実装がある場合、これをnewFactoryの引数として指定できます。

次の文はJdbcRowSetオブジェクトjdbcRsを作成し、このデータベース接続プロパティを構成します。

      jdbcRs = myRowSetFactory.createJdbcRowSet();

      jdbcRs.setUrl("jdbc:myDriver:myAttribute");
      jdbcRs.setUsername(username);
      jdbcRs.setPassword(password);

RowSetFactoryインタフェースには、JDBC 4.1以降で使用可能な異なるタイプのRowSet実装を作成するための次のメソッドが含まれています。


Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved.