製品/サービス
ソリューション
ダウンロード
価格/ライセンス
サポート
研修/資格
パートナー
会社概要
Oracle Technology Network
Java SE 7に含まれるJDBC 4.1には、次の機能が導入されています。
try
Connection
ResultSet
Statement
RowSetFactory
RowSetProvider
try-with-resources文を使用すると、SQLExceptionやその他の例外が投げられたかどうかに関係なく、java.sql.Connectionオブジェクトやjava.sql.Statementオブジェクト、またjava.sql.ResultSetオブジェクトを自動的に解放できます。 try-with-resources文は、try文と1つ以上の宣言済みリソース(区切り文字としてセミコロンを使用)で構成されます。
SQLException
java.sql.Connection
java.sql.Statement
java.sql.ResultSet
詳しくは、The try-with-resources Statementを参照してください。
次の例では、Statementオブジェクトであるstmtを自動的に解放するため、try-with-resources文が使用されています。
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); } } }
次の文は、stmtという1つのリソースを宣言したtry-with-resources文であり、このオブジェクトはtryブロックの終了時に自動的に解放されます。
try (Statement stmt = con.createStatement()) { // ... }
RowSetFactoryのインスタンスを使用して、RowSetオブジェクトを作成できます。 次の例では、RowSetFactoryのインスタンスを使用して、JdbcRowSetオブジェクトであるjdbcRsが作成されています。
RowSet
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(); // ...
次の文では、デフォルトのRowSetFactory実装であるcom.sun.rowset.RowSetFactoryImplを使用して、RowSetProviderオブジェクトのmyRowSetFactoryが作成されています。
com.sun.rowset.RowSetFactoryImpl
myRowSetFactory
myRowSetFactory = RowSetProvider.newFactory();
また、使用しているJDBCドライバに固有のRowSetFactory実装が含まれる場合は、newFactoryの引数にこれを指定できます。
newFactory
次の文では、JdbcRowSetオブジェクトであるjdbcRsが作成され、データベース接続プロパティが設定されています。
jdbcRs = myRowSetFactory.createJdbcRowSet(); jdbcRs.setUrl("jdbc:myDriver:myAttribute"); jdbcRs.setUsername(username); jdbcRs.setPassword(password);
RowSetFactoryインタフェースには次のメソッドが含まれており、JDBC 4.1以降で使用できる各種のRowSet実装を作成できます。
createCachedRowSet
createFilteredRowSet
createJdbcRowSet
createJoinRowSet
createWebRowSet