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
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...)