While ResultSet.next () returning only one result

0

I have a problem, when I put the ResultSet.next() in while and I get the information in the Database column it returns only one result.

People table:

Pessoas:      Idade:
Marcos        22
Marcos        24
Marcos        25
Roberto       26
Roberto       21

Code:

private static String pegarTodasAsIdades(String pessoas) {
        query = "SELECT Idade FROM Pessoas WHERE Pessoas=?";
        try {
            ps = conn.prepareStatement(query);
            ps.setString(1, pessoas);
            rs = ps.executeQuery();
            while (rs.next()) {
                String idades = rs.getString("Idade");
                return idades+"\t";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "";
    }

But the above code only returns me the age '19' (first column)

Note:

conn = Connection
ps = PreparedStatement
rs = ResultSet
    
asked by anonymous 20.07.2018 / 21:12

2 answers

1

There is return within your while . When return is found, the method ends immediately. Therefore, when you read the first result, the method ends without any other results being processed.

Assuming that you are managing the connections correctly with conn (I think this assumption is false, but that is a subject for another question), your code should look like this:

private static final String IDADES_SQL =
        "SELECT Idade FROM Pessoas WHERE Pessoas = ?";

private static String pegarTodasAsIdades(String pessoas) {
    try (PreparedStatement ps = conn.prepareStatement(IDADES_SQL)) {
        ps.setString(1, pessoas);
        try (ResultSet rs = ps.executeQuery()) {
            StringBuilder idades = new StringBuilder();
            while (rs.next()) {
                idades.append(rs.getString("Idade")).append("\t");
            }
            return idades.toString();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimException(e);
    }
}

Do not let PreparedStatement , ResultSet , and Connection be fields in your DAO, unless you know a lot, but very well what you're doing. And remember to always use try-with-resources .

    
20.07.2018 / 21:25
1

There is a return in the middle of the while ... It is doing the while stop. Here's a solution:

private static String pegarTodasAsIdades(String pessoas) {
    query = "SELECT Idade FROM Pessoas WHERE Pessoas=?";
    try {
        ps = conn.prepareStatement(query);
        ps.setString(1, pessoas);
        rs = ps.executeQuery();
        String idades = "";
        while (rs.next()) {
            idades += rs.getString("Idade") + "\t";
        }
        return idades;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return "";
}
    
20.07.2018 / 21:24