16.10.2015 Views

Getting Startedwith pureQuery

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

13.4.1 Writing a ResultHandler implementation<br />

Chapter 13 – Handlers 269<br />

The ResultHandler interface has the method handle, shown in figure Listing<br />

13.9.<br />

RES handle(ResultSet resultSet);<br />

Listing 13.9 - The handle method in the ResultHandler interface<br />

The parameter to the handle method is a java.sql.ResultSet object. This is the<br />

query result of the SQL statement. Your implementation of the handle method must use<br />

resultSet to create and return the object that you want your annotated or inline method<br />

to return.<br />

As an example, imagine that you wanted an annotated or inline method to return a String<br />

describing the query result. Spaces should separate the values of the columns, and line<br />

breaks should separate the rows. This would probably not be a very useful way to return a<br />

query result, but we are using this just as a simple example. Listing 13.10 shows how you<br />

could implement such a handler.<br />

import java.sql.ResultSet;<br />

import java.sql.SQLException;<br />

import com.ibm.pdq.runtime.handlers.ResultHandler;<br />

public class SimpleStringResultHandler implements ResultHandler<br />

{<br />

public String handle (ResultSet resultSet)<br />

{<br />

StringBuilder result = new StringBuilder ();<br />

try {<br />

int columns = resultSet.getMetaData ().getColumnCount ();<br />

while (resultSet.next ()) {<br />

for (int i = 0; i < columns; i++) {<br />

result.append (resultSet.getString (i) + " ");<br />

}<br />

result.append ("\n");<br />

}<br />

}<br />

catch (SQLException e) {<br />

throw new RuntimeException ("An error occurred while processing the<br />

query result.", e);<br />

}<br />

return result.toString ();<br />

}<br />

}<br />

Listing 13.10 - An example implementation of ResultHandler

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!