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, 2013, Oracle and/or its affiliates. All rights reserved.