blob snippets

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

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

This example works with Oracle:

private Blob getBlob(Connection connection, String data)
{
  BLOB blob = BLOB.createTemporary(connection, true, BLOB.DURATION_SESSION);

  try
  {
      blob.open(BLOB.MODE_READWRITE);
      blob.putBytes(1, data.getBytes("UTF-8")); // Consider streaming, if data size is unknown. Note that setBytes doesn't work
  }
  catch(UnsupportedEncodingException ex)
  {
      throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  }
  catch(SQLException ex)
  {
      throw new RuntimeException("Unable to get a blob for '" + data + "'", ex);
  }
  finally
  {
      try { if(blob != null) blob.close(); } catch(Exception ex) {};
  }
}

Then use the method like this:

Connection connection = getConnection();
PreparedStatement statement = getPreparedStatement(yer sequel);

statement.setBlob(1, getBlob(connection,  <Mao's Little Red Book>));

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

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

This example works with Oracle:

private String getBlobAsString(Blob blob)
{
    StringBuffer result = new StringBuffer();
    
    if ( blob != null ) 
    {
        int read = 0;
        Reader reader = null;
        char[] buffer = new char[1024];
                                
        try
        {
            reader = new InputStreamReader(blob.getBinaryStream(), "UTF-8");

            while((read = reader.read(buffer)) != -1) 
            {
                result.append(buffer, 0, read);
            }
        }
        catch(SQLException ex)
        {
            throw new RuntimeException("Unable to read blob data.", ex);
        }
        catch(IOException ex)
        {
            throw new RuntimeException("Unable to read blob data.", ex);
        }
        finally
        {
            try { if(reader != null) reader.close(); } catch(Exception ex) {};
        }
    }
    
    return result.toString();
}

Then use the method like this:

ResultSet resultSet = your JDBC result set;

String utf8 = getBlobAsString(resultSet.getBlob("xml"));