Reputation: 9
I have created a method which should return a cell from my database (it's a varchar variable) and assign it to a String. Another method is then called that takes that String and assigns variables to a User object which is then added to an array list. The SQL query statement works fine in PHPMyAdmin, but in Java the method runs until just after System.out.println("Getting followers...");
Then for some reason it stops working. I don't understand it because I have used the code from this method to retrieve different variables in other parts of the program without any problems, but whenever I try to get this one variable from the database, it fails to work properly.
Thanks in advance for all your help.
public ArrayList<User> returnFollowers(){
ArrayList<User> userArray = new ArrayList<User>();
User user = new User();
try{
Class.forName("com.mysql.jdbc.Driver");
statement = connection.createStatement();
result = statement.executeQuery("SELECT Follower FROM User_Followers WHERE Username = 'Apple123'");
if(!result.next()){
System.out.println("No results found");
}
else{
while(result.next()){
}
System.out.println("Getting followers...");
String userID = result.getString("Follower");
user.createUser(userID);
userArray.add(user);
}
}
catch(ClassNotFoundException error){
System.out.println("Error: " + error.getMessage());
}
catch(SQLException error){
System.out.println("Error " + error.getMessage());
}
finally{
if(connection != null){
try{
connection.close();
}
catch(SQLException ignore){
}
}
if(statement != null){
try{
statement.close();
}
catch(SQLException ignore){
}
}
}
return userArray;
}
Upvotes: 0
Views: 71
Reputation: 46871
First while
loop is empty
Second The problem is with result.next()
that you have already called in if
clause.
Now you are calling result.next()
again in while
clause hence first record is already skipped.
change while
loop in do-while
in this case.
Do in this way:
if(!result.next()){
System.out.println("No results found");
}else{
do{
System.out.println("Getting followers...");
String userID = result.getString("Follower");
user.createUser(userID);
userArray.add(user);
}while(result.next());
}
Upvotes: 2
Reputation: 159864
You're calling result.getString("Follower")
outside the scope of the while
loop so there are no more records available. It's probably better just to use a single while loop here
Upvotes: 0