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 skipping a row. So How can I avoid that or Reset the Position of rs.next()
method?
String searchword = Searchtf.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection(url, db_username, db_password);
java.sql.Statement stat = con.createStatement();
String searchQuery = "SELECT * FROM user WHERE Name LIKE '" + searchword + "' ";
java.sql.ResultSet rs = stat.executeQuery(searchQuery);
if (rs.next()) {
while (rs.next()) {
System.out.print(rs.getString("idUser") + " ,");
System.out.print(rs.getString("Name") + " ,");
System.out.print(rs.getString("Email") + " ,");
System.out.println(rs.getString("country") + " .");
}
} else {
JOptionPane.showMessageDialog(null, "Not Found");
}
} catch (Exception ex) {
ex.printStackTrace();
}
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...)
See more on this question at Stackoverflow