'How do you fetch all rows data but only display only 10 rows in JDBC?
I am writing a small program to interact with databae. And I want JDBC to get all the data but only display 10 rows. I know I need to add some conditions inside the while loop, but not sure how to do it.
String queries [] = {query1,query2,query3};
//loop for running every queries
for(int j = 0; j < 3; j++){
long startTime = System.currentTimeMillis();
ResultSet rs = stmt.executeQuery(queries[j]);
ResultSetMetaData rsMetaData = rs.getMetaData();
int count = rsMetaData.getColumnCount();
//get column name
for(int i = 1; i <= count; i++) {
System.out.print(rsMetaData.getColumnName(i) + ", ");
}
System.out.print("\n");
//get rows
while(rs.next()) {
for(int i = 1; i <= count; i++) {
System.out.print(rs.getString(i) + ", ");
}
System.out.print("\n");
}
System.out.print("------------------------------------");
long endTime = System.currentTimeMillis();
System.out.println("\nThe query " + (j+1) + " took "+(endTime-startTime)+" milliseconds.\n");
rs.close();
}
Solution 1:[1]
There are many ways to limit outputting just 10 rows. Here are just 2 examples.
Using a counter:
int rowCounter = 0;
while(rs.next()) {
for(int i = 1; i <= count; i++) {
System.out.print(rs.getString(i) + ", ");
}
System.out.print("\n");
rowCounter++; // after printing a row, increment counter
if (rowCounter >= 10) { // counted at least 10 rows
break; // break out of the while-loop
}
}
Using ResultSet.getRow():
while(rs.next() && rs.getRow() <= 10) { // ResultSet.getRow() returns the current row index
for(int i = 1; i <= count; i++) {
System.out.print(rs.getString(i) + ", ");
}
System.out.print("\n");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KompjoeFriek |
