Reputation: 1
I want to use while(rs.next())
to traverse the UserInfo
table. There are seven records in UserInfo
table, but I only got the first record. After I had joined the codes of rs.getRow();
, I got the result what I want.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
while(rs.next())
{
String strName="Name is "+rs.getString(3)+";";
String intAge="Age is "+rs.getInt(5)+";";
String strCompany="Company is "+rs.getString(4)+".<br>";
//int rowNum=rs.getRow();
out.println(strName+intAge+strCompany);
}
out.println("Succeed in visiting UserInfo table.");
}catch(SQLException e){
out.println("Failed to query.");
}
I don't want to use rs.getRow();
. How should I deal with this problem?
Upvotes: 0
Views: 118
Reputation: 14731
Your code does appear to be fine except the String part.If you are using String to hold a record, then you wouldn't be able to display all 7 records.
Thus try using collection object like ArrayList. And of course you should close connections in finally block.
try{
Statement stmt=conn.createStatement();
String queryStr="SELECT * FROM UserInfo";
ResultSet rs=stmt.executeQuery(queryStr);
List<String> list = new ArrayList<String>();
while(rs.next()){
list.add(rs.getString(3));
}
System.out.println("rows "+list.size());
}catch(SQLException e){
out.println("exception "+e.getMessage());
}
finally{
rs.close();
stmt.close();
conn.close();
}
This is good example of how you should be retrieving values from database using collection object. http://theopentutorials.com/tutorials/java/jdbc/how-to-retrieve-all-rows-from-mysql-table-using-jdbc/
Upvotes: 1
Reputation: 538
rs.next
only tells you if there is a next record.
When you run
ResultSet rs=stmt.executeQuery(queryStr);
This already places the data from the first record into variable rs
.
In order to advance to the next record you need to run rs.getRow
but only if there is a
next record (check with rs.next).
Upvotes: 0
Reputation: 1235
rs.next()
Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row;
Upvotes: 0