Java Database Connectivity: Retrieving Result

A table of data is represented in the JDBC by the ResuitSet interface. The ResuitSet objects are usually generated by executing the SQL statements that query the database. A pointer points to a particular row of the ResuitSet object at a time. This pointer is called cursor. The cursor is positioned before the first row when the ResuitSet object is generated. To retrieve data from a row of ResuitSet, the cursor must be positioned at the row. The ResuitSet interface provides methods to move this cursor.

next()

  • This method on the Resuitset object moves the cursor to the next row of the result set.
  • It returns true/false depending upon whether there are more rows in the result set.

Since the next() method returns false when there are no more rows in the Resuitset object, it can be used in a while loop to iterate through the result set as follows:

String query = “SELECT * from users”;

ResultSet rs = stmt.executeQuery(query);

while(rs.next()) {

//process it

}

The Resuitset interface provides reader methods for retrieving column values from the row pointed to by the cursor. These have the form getXxx(), where Xxx is the name of the data type of the column. For example, if data types are string and int, the name of the reader methods are getstring() and getint(), respectively.

Values can be retrieved using either the column index or the name of the column. Using the column index, in general, is more efficient. The column index starts from 1. The following example illustrates how to retrieve data from a Resuitset object.

String query = “SELECT * from users”;

ResultSet rs = stmt.executeQuery(query);

while(rs.next()) {

String login = rs.getString(“login”);

String password = rs.getString(“password”);

System.out.println(login+”\t”+password);

}

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *