Friday, 3 July 2015

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

WRITE:

To transform String value into blob just execute your_string.getBytes();

String blobValue = "long blob";
bytes[] bytes = blobValue.getBytes();
int rows = getJdbcTemplate().update("update MY_TABLE set BLOB_COLUMN = ? where ROWID = '1'", bytes);

READ:

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

public static String sqlBlobToString(Blob blob) {

StringBuilder stringBuilder = new StringBuilder();

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


Querying from database:

String s = sqlBlobToString(getJdbcTemplate().queryForObject("select BLOB_COLUMN from MY_TABLE where ROWID = '1'", Blob.class));

Note: I am using java.sql.Blob

No comments:

Post a Comment