I will post it, thinking that if someone made the same mistake.
I thought rs.next () was "a method that only determines if there is a ResultSet next",
In addition, there seems to be a function to "go to the next line from the current position and place the cursor". (For more information, see the Oracle page (https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html).)
mistake.java
ResultSet rs = stmt.executeQuery(sql);
//If there is no result, null is returned
if(rs.next()){ //← Here, the cursor is on the first line of the result
return null;
}
//2.Generate a list
while (rs.next()) { //← Here, the cursor is on the second line of the result
list.add(rs.getString("name")); //← Here, the name of the second line is taken as a result
}
I was coding as above. Wrong. The list generated by java is one line less than hitting SQL with a command! I was worried for an hour ... That should be it too.
Since the cursor has hit the first line of the result before turning with while, When I tried to turn it with while, the cursor hit the second line of the result, The first line of the result was not added to the list.
For reference, if you do the following, it seems that processing when the result is 0 is also applied.
Correct answer.java
ResultSet rs = stmt.executeQuery(sql);
//Add data to the list
while (rs.next()) {
list.add(rs.getString("Field name"));
}
//If the list is from, return null
if(list.isEmpty()){
return null;
}
Some source code has been modified. Thank you for pointing out saka1029 and Kilisame!
Recommended Posts