如何正确清理Java中的JDBC资源? [英] How to properly clean up JDBC resources in Java?
问题描述
清理JDBC资源时,什么是最佳实践?为什么?我将示例保持简短,因此仅清理了ResultSet.
What is considered best practices when cleaning up JDBC resources and why? I kept the example short, thus just the cleaning up of the ResultSet.
finally
{
if(rs != null)
try{ rs.close(); } catch(SQLException ignored) {}
}
与
finally
{
try{ rs.close(); } catch(Exception ignored) {}
}
我个人比较喜欢第二种选择,因为它有点短.任何对此的投入,我们深表感谢.
Personally I favour the second option since it is a bit shorter. Any input on this is much appreciated.
推荐答案
如今,JDK 7为您提供了清理资源的最简单选择:
Nowadays JDK 7 gives you the easiest option to clean up resources:
String query = "select COF_NAME, PRICE from COFFEES";
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
float price = rs.getFloat("PRICE");
System.out.println(coffeeName + ", " + price);
}
}
try语句可确保在语句末尾关闭每个资源.请参见 http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
The try statement ensures that each resource is closed at the end of the statement. See http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
这篇关于如何正确清理Java中的JDBC资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!