Avoiding skipping a row By next() Method of ResultSet

后端 未结 6 1994
野性不改
野性不改 2021-01-15 00:34

This is a simple code print some rows from a Database. but When I execute this nothing is print on screen. I figured that the problem is rs.next() method is ski

6条回答
  •  逝去的感伤
    2021-01-15 01:29

    First, stop building SQL like that - use parameterized SQL and a PreparedStatement. Your current code is vulnerable to SQL injection attacks.

    Basically, don't call rs.next() twice in a row (first in the if then in the while)... you can easily do that by converting your while loop into a do/while loop:

    if (rs.next()) {
        do {
            System.out.print(rs.getString("idUser") + " ,");
            System.out.print(rs.getString("Name") + " ,");
            System.out.print(rs.getString("Email") + " ,");
            System.out.println(rs.getString("country") + " .");
        } while (rs.next());
    }
    

    Or just have the while loop, with a separate variable to detect that you've seen some results:

    bool anyResults = false;
    while (rs.next()) {
        anyResults = true;
        System.out.print(rs.getString("idUser") + " ,");
        System.out.print(rs.getString("Name") + " ,");
        System.out.print(rs.getString("Email") + " ,");
        System.out.println(rs.getString("country") + " .");
    }
    if (!anyResults) {
        JOptionPane.showMessageDialog(null, "Not Found");
    }
    

    (Additionally, you should use try-with-resources to close your ResultSet etc, and just printing a stack trace to stdout is almost never the appropriate way to handle exceptions...)

提交回复
热议问题