v If the iterator is a positioned iterator, the number of columns in the result set
must match the number of columns in the iterator. In addition, the data type of
each column in the result set must match the data type of the corresponding
column in the iterator.
v If the iterator is a named iterator, the name of each accessor method must match
the name of a column in the result set. In addition, the data type of the object
that an accessor method returns must match the data type of the corresponding
column in the result set.
The code in Figure 46 builds and executes a query using a JDBC call, executes an
iterator conversion statement to convert the JDBC result set to an SQLJ iterator,
and retrieves rows from the result table using the iterator.
Notes to Figure 46:
Note Description
1 This SQLJ clause creates the named iterator class ByName, which has accessor
methods LastName() and HireDate() that return the data from result table columns
LASTNAME and HIREDATE.
2 This statement and the following two statements build and prepare a query for
dynamic execution using JDBC.
3 This JDBC statement executes the SELECT statement and assigns the result table
to result set rs.
4 This iterator conversion clause converts the JDBC ResultSet rs to SQLJ iterator
nameiter, and the following statements use nameiter to retrieve values from the
result table.
5 The nameiter.close() method closes the SQLJ iterator and JDBC ResultSet rs.
Generating JDBC ResultSets from SQLJ iterators: Use the getResultSet method to
generate a JDBC ResultSet from an SQLJ iterator. Every SQLJ iterator has a
getResultSet method. After you convert an iterator to a result set, you need to fetch
rows using only the result set.
The code in Figure 47 on page 141 generates a positioned iterator for a query,
converts the iterator to a result set, and uses JDBC methods to fetch rows from the
#sql public iterator ByName(String LastName, Date HireDate); 1
public void HireDates(ConnectionContext connCtx, String whereClause)
{
ByName nameiter; // Declare object of ByName class
Connection conn=connCtx.getConnection();
// Create JDBC connection
Statement stmt = conn.createStatement(); 2
String query = "SELECT LASTNAME, HIREDATE FROM EMPLOYEE";
query+=whereClause; // Build the query
ResultSet rs = stmt.executeQuery(query); 3
#sql [connCtx] nameiter = {CAST :rs}; 4
while (nameiter.next())
{
System.out.println( nameiter.LastName() + " was hired on "
+ nameiter.HireDate());
}
nameiter.close(); 5
stmt.close();
}
Figure 46. Converting a JDBC result set to an SQLJ iterator
140 Application Programming Guide and Reference for Java
™