Register now and start sharing your code snippets.
-->

How to read UTF-8 data from an Oracle BLOB column with Java and JDBC

Java posted about 1 year ago by christian

This example works with Oracle:

   1  private String getBlobAsString(Blob blob)
   2  {
   3      StringBuffer result = new StringBuffer();
   4      
   5      if ( blob != null ) 
   6      {
   7          int read = 0;
   8          Reader reader = null;
   9          char[] buffer = new char[1024];
  10                                  
  11          try
  12          {
  13              reader = new InputStreamReader(blob.getBinaryStream(), "UTF-8");
  14  
  15              while((read = reader.read(buffer)) != -1) 
  16              {
  17                  result.append(buffer, 0, read);
  18              }
  19          }
  20          catch(SQLException ex)
  21          {
  22              throw new RuntimeException("Unable to read blob data.", ex);
  23          }
  24          catch(IOException ex)
  25          {
  26              throw new RuntimeException("Unable to read blob data.", ex);
  27          }
  28          finally
  29          {
  30              try { if(reader != null) reader.close(); } catch(Exception ex) {};
  31          }
  32      }
  33      
  34      return result.toString();
  35  }

Then use the method like this:

   1  ResultSet resultSet = your JDBC result set;
   2  
   3  String utf8 = getBlobAsString(resultSet.getBlob("xml"));
   4  

Tagged oracle, blob, utf-8, java

How to write UTF-8 data to an Oracle BLOB column with Java and JDBC

Java posted about 1 year ago by christian

This example works with Oracle:

   1  private Blob getBlob(Connection connection, String data)
   2  {
   3    BLOB blob = BLOB.createTemporary(connection, true, BLOB.DURATION_SESSION);
   4  
   5    try
   6    {
   7        blob.open(BLOB.MODE_READWRITE);
   8        blob.putBytes(1, data.getBytes("UTF-8")); // Consider streaming, if data size is unknown. Note that setBytes doesn't work
   9    }
  10    catch(UnsupportedEncodingException ex)
  11    {
  12        throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  13    }
  14    catch(SQLException ex)
  15    {
  16        throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  17    }
  18    finally
  19    {
  20        try { if(blob != null) blob.close(); } catch(Exception ex) {};
  21    }
  22  }

Then use the method like this:

   1  Connection connection = getConnection();
   2  PreparedStatement statement = getPreparedStatement(yer sequel);
   3  
   4  statement.setBlob(1, getBlob(connection,  <Mao's Little Red Book>));

Tagged oracle, blob, jdbc, java, utf-8