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");
Nettogrof
2,1362 gold badges15 silver badges22 bronze badges
4 Answers 4
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");
answered Mar 3, 2012 at 7:12
juergen d
205k40 gold badges305 silver badges377 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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"));
}
answered Mar 3, 2012 at 7:13
Yann Ramin
33.2k3 gold badges63 silver badges83 bronze badges
Comments
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"));
}
answered Mar 3, 2012 at 7:13
Shakti Singh
86.8k21 gold badges142 silver badges156 bronze badges
Comments
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");
answered Mar 3, 2012 at 10:36
1218985
8,1122 gold badges29 silver badges33 bronze badges
Comments
default