Javaã®AutoCloseableã¨ããããã¤
æ å ±è±å¯ã§æ¯ãããã®ã好ããªç§ã§ãããããã«Javaã®éçºã§ã¯ãããããJDK 7ã使ã£ã¦ãããããããªããã¨æãå§ãã¦ãã¾ããã
AutoCloseableã¯ç°¡åã ããã¡ãã£ã¨ä¾¿å©ãããªã®ã§ä½¿ã£ã¦ã¿ããã
try ( Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); ) { while (rset.next()) { // ... } }
tryã®æå¾ã«catchãfinallyããªãã®ã¯ã¡ãã£ã¨éåæããããã©ãããã¤ãã® if (null != conn) try { conn.close(); } catch (SQLException e) {} ãæ¸ããªãã¦è¯ãã®ã¯ããã§ãããããããèªåã¯ãã¼ãºä¸ã«çºçããä¾å¤ã¯ãæ¡ãã¤ã¶ãã¦ãã¾ãã®ã§ã¯ãªããã¡ããã¨Suppressedã¨ãã¦ãå ã®ä¾å¤ã«è¿½å ãã¦ããã¦ãããã¿ããã§ããï¼Throwable#getSuppressed()ã§åå¾å¯è½ï¼
ã§ããããnullãã§ãã¯ã¨closeã ããã£ã¦æ¬²ããã®ã«ãããã¯æ¸ããªããã§ããã
Connection conn = null; Statement stmt = null; ResultSet rset = null; try ( // ã³ã³ãã¤ã«ã¨ã©ã¼ conn, stmt, rset ) { // ... }
ã¤ã¾ããä½ãå°ããã¨ããã¨ãtryãããã¯ã®éå§ã¨åæã«çæãããã®ããAutoCloseableã®æ©æµãåããããªãã¨ãããã¨ã§ãã
try ( Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ) { stmt.setInt(1, 1); stmt.setInt(2, 2); // ... // ãã¦ãããã¤ãã©ã解æ¾ããï¼ ResultSet rset = stmt.executeQuery(); }
ã¾ãããã®å ´åã¯tryããã¹ãããã°OKã§ããã
try ( Connection conn = dataSource.getConnection(); java.sql.PreparedStatement stmt = conn.prepareStatement(sql); ) { stmt.setInt(1, 1); stmt.setInt(2, 2); // ... try (ResultSet rset = stmt.executeQuery()) { while (rset.next()) { // ... } } }
è¨è¿°ãåé·ã«ãªãã®ãå«ã§AutoCloseableã使ãããã®ã«ããã¹ããæ·±ããªã£ã¦ãã¾ãã¨ããã®ã§ã¯ããªãã ãååæããæ°åã«ãªã£ã¦ãã¾ãã¾ãã
ããããããæ°æã¡ã§ãæã¹ã¿ãã¯ãªã¼ãã¼ããã¼ã§æ å ±ãæ¼ã£ã¦ã¿ã¾ããã
æ ¹æ¬çãªè§£æ±ºã«ã¯ãªãã¾ããããResultSetã¯closeããªãã¦è¯ãããã§ãã
http://stackoverflow.com/questions/11454999/closing-resultset-in-java-7
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
ãµãã
ã¾ããããã¨ãã£ãçµè«ããªã«ããªãã
Javaã«ãã´ãªã追å ããããã¨æãã»ã©ã®æåããªãã
ããã¾ã