ResultSet Object with Example

The ResultSet Object:

  • JDBC returns the results of a query in a ResultSet object.
  • A ResultSet maintains a cursor pointing to its current row of data.
  • Use next() to step through the result set row by row.
  • getString(), getInt(), and so on assign each value to a Java variable.
The getXXX() Methods:
The ResultSet class has several methods that retrieve column values for the current row. Each of these getXXX() methods attempts to convert the column value to the specified Java type and returns a suitable Java value. For example, getInt() gets the column value as an int, getString() gets the column value as a String, and getDate() returns the column value as a Date.

How to Process the Results:

1. Step through the result set.


2. Use getXXX() to get each column value.

String name = rs.getString("NAME");
String id = rs.getInt("ID");

Obtaining the Column Values :

  • Each of the getXXX() methods has two versions, allowing the programmer to specify the column by number or by name.
  • Specifying columns by number: When column numbers are used as input to the getXXX() methods, the columns are numbered from 1.
  • Specifying columns by name: When column names are used as input to the getXXX() methods, the column names are case-insensitive.
  • The column names option should be used when column names are used in the SQL query. For columns that were not explicitly named in the query, it is better to use column numbers. ResultSet provides a method called findColumn() that returns the column number for a given column name.
  • getString
  • The example on the slide uses getString() to return the column values. getString() can be used to retrieve any of the basic SQL data types. It is the easiest method to use for visual applications, when you want to display or print the data. It can also be used when the end user will update the data, which you then convert to a SQL UPDATE statement.
  • getBigDecimal
  • All of the getXXX() methods require a single parameter, except for getBigDecimal(colname, scale) and getBigDecimal(colindex, scale), both of which require a second parameter for the number of digits to the right of the decimal.
  • Other getXXX() methods are covered in more detail later in this lesson.


Recent Posts