Friday, 3 July 2015

How to write / read CLOB to / from Oracle database?

WRITE:

there is no problems with clob saving into db - just keep it in String value and regularly save it:

String clobValue = "long clob";
int rows = getJdbcTemplate().update("update MY_TABLE set CLOB_COLUMN = ? where ROWID = '1'", clobValue);

READ:

we can either read clob from database in Clob class or transform into String. To transform it into String we will need additional custom method:

public static String sqlClobToString(Clob clob) {

StringBuilder stringBuilder = new StringBuilder();

try(BufferedReader bufferedReader = new BufferedReader(clob.getCharacterStream()) {
       while ((string = bufferedReader.readLine()) != null) {
              stringBuilder.append(string);
       }
 } catch (IOException e) {
       throw new RuntimeException(e);
}
return stringBuilder;
}

Querying from database:

String s = sqlClobToString(getJdbcTemplate().queryForObject("select CLOB_COLUMN from MY_TABLE where ROWID = '1'", Clob.class));

Note: I am using java.sql.Clob

No comments:

Post a Comment