【发布时间】:2011-12-25 08:59:23
【问题描述】:
我有一种使用 JDBC 从数据库中获取用户的方法:
public List<User> getUser(int userId) {
String sql = "SELECT id, name FROM users WHERE id = ?";
List<User> users = new ArrayList<User>();
try {
Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, userId);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
我应该如何使用 Java 7 try-with-resources 来改进这段代码?
我尝试过使用下面的代码,但它使用了许多try 块,并没有提高可读性。我应该以其他方式使用try-with-resources吗?
public List<User> getUser(int userId) {
String sql = "SELECT id, name FROM users WHERE id = ?";
List<User> users = new ArrayList<>();
try {
try (Connection con = DriverManager.getConnection(myConnectionURL);
PreparedStatement ps = con.prepareStatement(sql);) {
ps.setInt(1, userId);
try (ResultSet rs = ps.executeQuery();) {
while(rs.next()) {
users.add(new User(rs.getInt("id"), rs.getString("name")));
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
【问题讨论】:
-
在你的第二个例子中,你不需要内部的
try (ResultSet rs = ps.executeQuery()) {,因为A ResultSet object is automatically closed by the Statement object that generated it -
@AlexanderFarber 不幸的是,驱动程序无法自行关闭资源存在臭名昭著的问题。 Hard Knocks 教我们始终明确关闭所有 JDBC 资源,使用
Connection、PreparedStatement和ResultSet周围的 try-with-resources 也更容易。没有理由不这样做,因为 try-with-resources 使它变得如此简单,并使我们的代码更加自我记录我们的意图。
标签: java jdbc java-7 try-with-resources