Retrieving JSON documents from a ResultSet
You can query a relational table, and then convert the ResultSet that you retrieve to a com.ibm.db2.jcc.json.DB2JSONResultSet object, which holds the data in JSON format. After you create the DB2JSONResultSet object, you can use methods on that object to retrieve the JSON documents or JSON snippets.
Procedure
To retrieve JSON documents or snippets from ResultSet objects, follow this procedure.
Examples
The numbers to the right of statements in the following examples correspond to the previously described steps.
Example: Use DB2JSONResultSet.getCurrentRow to retrieve one row of a JSON document at a time.
sql = "SELECT EMPNO, SALARY FROM EMPLOYEE";
ResultSet rs =
stmt.executeQuery(sql); 1
// ResultSet contains a CHAR
// and a DECIMAL column
DB2JSONResultSet jsonrs = ((DB2ResultSet) rs).toJSONResultSet(); 2
// DB2JSONResultSet contains
// String and Number fields
while(jsonrs.next()) {
String row = json.getCurrentRow(); 3
…
// Process row
}
jsonrs.close(); // Close the DB2JSONResultSet 4
Example: Use DB2JSON.toJSONString to retrieve an entire JSON document into a String.
sql = "SELECT EMPNO, PHONENO FROM EMPLOYEE";
ResultSet rs =
stmt.executeQuery(sql); 1
// ResultSet contains a CHAR
// and a DECIMAL column
DB2JSONResultSet jsonrs = ((DB2ResultSet) rs).toJSONResultSet(); 2
// DB2JSONResultSet contains
// String and Number fields
String jsondoc = json.toJSONString(); 3
…
// Process contents of string
jsonrs.close(); // Close the DB2JSONResultSet 4
Example: Use DB2JSONResultSet.getAsciiStream to read the JSON document into an AsciiStream.
sql = "SELECT EMPNO, PHONENO FROM EMPLOYEE";
ResultSet rs =
stmt.executeQuery(sql); 1
// ResultSet contains a CHAR
// and a DECIMAL column
DB2JSONResultSet jsonrs = ((DB2ResultSet) rs).toJSONResultSet(); 2
// DB2JSONResultSet contains
// String and Number fields
InputStream is = jsonrs.getAsciiStream(); 3
char [] buff = new char [1024];
int b = 0;
do { // Read and print AsciiStream contents
b = is.read ();
if (b > 0) {
System.out.print ((char)b);
}
} while (b > 0);
is.close();
jsonrs.close(); // Close the DB2JSONResultSet 4
Example: Use DB2JSONResultSet.getCharacterStream to retrieve an entire JSON document into a character stream. Then read the document contents into a buffer and print them.
sql = "SELECT EMPNO, PHONENO FROM EMPLOYEE";
ResultSet rs =
stmt.executeQuery(sql); 1
// ResultSet contains a CHAR
// and a DECIMAL column
DB2JSONResultSet jsonrs = ((DB2ResultSet) rs).toJSONResultSet(); 2
// DB2JSONResultSet contains
// String and Number fields
Stream reader = jsonrs.getCharacterStream (); 3
char [] buff = new char[1024];
int len = 0;
do { // Read and print CharacterStream contents
len = reader.read(buff);
if (len > 0) {
System.out.println(String.copyValueOf(buff,0,len));
}
}
reader.close();
jsonrs.close(); // Close the DB2JSONResultSet 4