try-with-resources with JDBC

I realize this was long ago answered but want to suggest an additional approach that avoids the nested try-with-resources double block.

public List<User> getUser(int userId) { try (Connection con = DriverManager.getConnection(myConnectionURL); PreparedStatement ps = createPreparedStatement(con, userId); ResultSet rs = ps.executeQuery()) { // process the resultset here, all resources will be cleaned up } catch (SQLException e) { e.printStackTrace(); } } private PreparedStatement createPreparedStatement(Connection con, int userId) throws SQLException { String sql = "SELECT id, username FROM users WHERE id = ?"; PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, userId); return ps; }

猜你喜欢

转载自www.cnblogs.com/kakaisgood/p/10796304.html