Search code examples
javajdbcderbyclob

Converting from String to Clob using setString() not working


I am trying to convert a String into a Clob to store in a database. I have the following code:

Clob clob = connection.createClob();
System.out.println("clob before setting: " + clob);
clob.setString(1,"Test string" );
System.out.println("clob after setting: " + clob);
System.out.println("clob back to string: " + clob.toString());

When I run this the Clob is not being set, the output is as follows:

clob before setting: org.apache.derby.impl.jdbc.EmbedClob@1f5483e
clob after setting: org.apache.derby.impl.jdbc.EmbedClob@1f5483e
clob back to string: org.apache.derby.impl.jdbc.EmbedClob@1f5483e

Everywhere I look says to use the setString method, I have no idea why this isn't working for me.


Solution

  • You don't need the intermediate Clob instance, just use setString() on the PreparedStatement:

    PreparedStatement stmt = connection.prepareStatement("insert into clob_table (id, clob_column) values (?,?)";
    stmt.setInt(1, 42);
    stmt.setString(2, "This is the CLOB");
    stmt.executeUpdate();
    connection.commit();