I'm trying to retrieve a Clob field from an Oracle Database in a Java Spring project, but I'm having issues.
First, I made a query using a Spring object called SqlRowSet:
String query = sqlQueries.getProperty("THE_QUERY");
SqlRowSet rs = select.queryForRowSet(query, new HashMap<String, Object>());
After that I iterate over the object and start getting the information from the fields:
while (rs.next()) {
String name = rs.getString("name");
}
When I get the results of the query, I get sometihng like this:
name=javax.sql.rowset.serial.SerialClob@435dc43
I tried several things, but I'm not able to get the information from the field, which is an String on the end (not sure why the database creators used clob as the data type).
Do someone know how to get this information?
I found the answer combining two stackoverflow questions:
Spring SqlRowSet getting Clob as String using JdbcTemplate
Most efficient solution for reading CLOB to String, and String to CLOB in Java?
First, you need to create a Clob object, and then work on a method to extract the string from the Clob object. My code looks like the following and it works:
Clob clobObject = (Clob)rs.getObject("name");
final StringBuilder sb = new StringBuilder();
try
{
final Reader reader = clobObject.getCharacterStream();
final BufferedReader br = new BufferedReader(reader);
int b;
while(-1 != (b = br.read()))
{
sb.append((char)b);
}
br.close();
String theName = sb.toString();
catch (Exception ex)
{
}