接続の作成/受信、データベースのクエリ、およびおそらく結果の処理という一般的な JDBC イディオムを、Java 7 の自動リソース管理である try-with-resources ステートメントと統合するにはどうすればよいですか? (チュートリアル)
Java 7 より前では、通常のパターンは次のようなものでした。
Connection con = null;
PreparedStatement prep = null;
try{
con = getConnection();
prep = prep.prepareStatement("Update ...");
...
con.commit();
}
catch (SQLException e){
con.rollback();
throw e;
}
finally{
if (prep != null)
prep.close();
if (con != null)
con.close();
}
Java 7 では、次のことができます。
try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){
...
con.commit();
}
Connection
これでとが閉じますPreparedStatement
が、ロールバックはどうでしょうか。接続は try ブロック内でのみ使用できるため、ロールバックを含む catch 句を追加できません。
try ブロックの外側でまだ接続を定義していますか? 特に接続プールが使用されている場合、ここでのベストプラクティスは何ですか?