user3369905
user3369905

Reputation: 61

How to use setClob() in PreparedStatement inJDBC

Here are the info:

  1. I have a String
  2. I want to insert a record in a table with the String in a column whose datatype is CLOB.
  3. I would like to use setClob() method of the preparedstatement.

So my question is how to create a Clob object from this String so that I can use setClob() method.

Thanks in advance, Naveen

Upvotes: 6

Views: 32214

Answers (6)

Dale
Dale

Reputation: 3547

My answer is slightly different than others...

I had a PreparedStatement, stmt, and was using stmt.setString(colIndex, value) for updates to my database that had a CLOB column.

This worked without fail for me when inserting and updating rows in the database table.

When others tested this code though they would occasionally see an exception occur:

ORA-22275: invalid LOB locator

It only seemed to happen on updates, not inserts - not sure why on that, when value was null. And I only ever had this occur with Oracle databases, not MSSQL or DB2.

Anyway to fix it I changed the logic to test for a null value

if (value == null) {
  stmt.setNull(colIndex, java.sql.Types.CLOB);
}
else {
  stmt.setString(colIndex, value);
}

This worked without fail for me and others!

Upvotes: 0

Visruth
Visruth

Reputation: 3450

You may create the clob from a connection object as follows

Connection con = null;// write code to make a connection object
Clob clob = con.createClob();
String str = "this is a stirng";
clob.setString(1, str );

PreparedStatement ps = null;// write code to create a prepared statement
ps.setClob(4, clob);

Or you may try the alternative code as follows :

//alternative way       
String str = "this is a stirng";
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

int parameterIndex = 1;
PreparedStatement ps = null;// write code to create a prepared statement
ps.setClob(parameterIndex, inputStreamReader);

Upvotes: 7

Dave Lyndon
Dave Lyndon

Reputation: 796

I had a specific variation of this issue which required to insert a clob into an Oracle database from java code running on that db. None of the answers here quite worked for me.

I eventually found solution, the trick being to use oracle.sql.CLOB

This the approach I discovered:

create table test_clob (
    c clob
);

create or replace and compile java source named java_clob_insert as

import java.sql.Connection;
import java.sql.PreparedStatement;
import oracle.sql.CLOB;
import java.io.Writer;

public class JavaClobInsert {

    public static void doInsert () {

        try {

            //create the connection and statement
            Connection oracleConn =
                (new oracle.jdbc.OracleDriver()).defaultConnection();

            String stmt = "INSERT INTO test_clob values (?)";

            PreparedStatement oraclePstmt = oracleConn.prepareStatement(stmt);

            //Imagine we have a mysql longtext or some very long string
            String s = "";
            for (int i = 0; i < 32768; i++) {
                s += i % 10;
            }

            //Initialise the Oracle CLOB
            CLOB clob;
            clob = CLOB.createTemporary(oracleConn, true, CLOB.DURATION_CALL);

            //Good idea to check the string is not null before writing to clob
            if (s != null) {
                Writer w = clob.setCharacterStream( 1L );
                w.write(s);
                w.close();
                oraclePstmt.setClob(1, clob);
            } else {
                oraclePstmt.setString(1, "");
            }

            //clean up
            oraclePstmt.executeUpdate();
            oracleConn.commit();
            oraclePstmt.close();
            oracleConn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/

create or replace procedure clob_insert as language java name 
    'JavaClobInsert.doInsert()';    
/

begin
    clob_insert;
end;
/

select *
from   test_clob; 

Upvotes: 2

valepu
valepu

Reputation: 3315

Today i had an issue with a Clob field because i was using "setString" to set the parameter, but then i had this error while testing with a very long string: "setString can handle only Strings with less than 32766 characters"

I used connection.createClob but it gave me this exception:

java.lang.AbstractMethodError: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.createClob()Ljava/sql/Clob;

So looking for this exception i found this using CLOB in java throwing exception and the accepted answer (using setCharacterStream instead of setClob) worked for me

Copy/Pasted from the accepted answer (so all credits are for a_horse_with_no_name )

StringReader reader = new StringReader(userAbout);
PreparedStatement insertClob = dbCon.prepareStatement("UPDATE user_data SET user_about=? WHERE user_id=?");
insertClob.setCharacterStream(1, reader, userAbout.length());
insertClob.setInt(2,userId);

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

If you want to write a String to CLOB column just use PreparedStatement.setString.

If you want to know how to create a CLOB from String this is it

    Clob clob = connection.createClob();
    clob.setString(1, str);

Upvotes: 10

TA Nguyen
TA Nguyen

Reputation: 473

For CLOB it is of String already. So, just use .setString() and that should work. One thing about ORACLE jdbc if you are using it, it like the CLOB INPUT parameter to be the last one in your statement especially with a large data.

Example:

INSERT INTO MY_TABL (NUM_COL, VARC_COL, VARC_COL, TS_COL, CLOB_COL) 
   VALUES(?,?,?,?,?);

As you can see, the CLOB_COL is of type CLOB and should be last so that when you do .setString(5) and 5 is the last index.

Upvotes: 2

Related Questions