我應(yīng)該如何使用jdbc來嘗試使用資源呢?我有一種使用JDBC從數(shù)據(jù)庫中獲取用戶的方法: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試著用資源來改進(jìn)這個(gè)代碼?我嘗試了下面的代碼,但是它使用了很多try塊,而不改進(jìn)可讀性太多了。我應(yīng)該用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;}
我應(yīng)該如何使用jdbc來嘗試使用資源呢?
動(dòng)漫人物
2019-07-27 15:15:12