0

Hi in the following code it only prints the first id and the first name from the table. How do yo get it to print out all of the results from the query and not only the first results? thanks

Statement stat = conn.createStatement();  

stat.execute("CREATE TABLE Test (Id VARCHAR(20), Name VARCHAR(20))");  
stat.execute("INSERT INTO Test VALUES ('1AA', 'John')");  
stat.execute("INSERT INTO Test VALUES ('2AA', 'George')");
stat.execute("INSERT INTO Test VALUES ('3AA', 'Richard')");


ResultSet result = stat.executeQuery("SELECT * FROM Test");  
result.next();  
System.out.println(result.getString("Name"));  
System.out.println(result.getString("Id"));
stat.execute("DROP TABLE Test");  

4 Answers 4

6

Use a while loop to iterate over all results:

...
ResultSet result = stat.executeQuery("SELECT * FROM Test");  
while(result.next()) {  
    System.out.println(result.getString("Name"));  
    System.out.println(result.getString("Id"));
}
stat.execute("DROP TABLE Test");  
Sign up to request clarification or add additional context in comments.

Comments

2

A ResultSet is an iterator, that is the next method provides an indication if there is more data present.

For instance:

while(result.next()) {
 System.out.println(result.getString("Name"));
}

Comments

1

You need to iterate through the result. You can use the while loop

 while(result.next())
 {  
        System.out.println(result.getString("Name"));  
        System.out.println(result.getString("Id"));
 }

Comments

1

You may iterate through the ResultSet to print all of the results from the query as shown below:

    stat.execute("CREATE TABLE Test (Id VARCHAR(20), Name VARCHAR(20))");  
    stat.execute("INSERT INTO Test VALUES ('1AA', 'John')");  
    stat.execute("INSERT INTO Test VALUES ('2AA', 'George')");
    stat.execute("INSERT INTO Test VALUES ('3AA', 'Richard')");


    ResultSet result = stat.executeQuery("SELECT * FROM Test");  

    while(result.next()) {
       System.out.println(result.getString("Name")+"\t"+result.getString("Id"));
       //OR
       //System.out.println(result.getString(1)+"\t"+result.getString(2));
    }

    stat.execute("DROP TABLE Test");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.