简体   繁体   English

如何在JPD中的PreparedStatement中使用setClob()

[英]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 . 我想在一个表中插入一个记录,其中String的数据类型为CLOB
  3. I would like to use setClob() method of the preparedstatement. 我想使用preparedstatement的setClob()方法。

So my question is how to create a Clob object from this String so that I can use setClob() method. 所以我的问题是如何从这个String创建一个Clob对象,以便我可以使用setClob()方法。

Thanks in advance, Naveen 提前谢谢,Naveen

If you want to write a String to CLOB column just use PreparedStatement.setString . 如果要将字符串写入CLOB列,只需使用PreparedStatement.setString

If you want to know how to create a CLOB from String this is it 如果您想知道如何从String创建CLOB,那就是它

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

You may create the clob from a connection object as follows 您可以按如下方式从连接对象创建clob

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);

For CLOB it is of String already. 对于CLOB,它已经是String。 So, just use .setString() and that should work. 所以,只需使用.setString()即可。 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. 关于ORACLE jdbc的一件事,如果您正在使用它,它就像CLOB INPUT参数一样,是您语句中的最后一个参数,特别是对于大数据。

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. 正如您所看到的,CLOB_COL的类型为CLOB,应该是最后一个,以便在执行时.setString(5)和5是最后一个索引。

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" 今天我遇到了Clob字段的问题,因为我使用“setString”来设置参数,但是在使用非常长的字符串进行测试时我遇到了这个错误:“setString只能处理少于32766个字符的字符串”

I used connection.createClob but it gave me this exception: 我使用了connection.createClob,但它给了我这个例外:

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 所以寻找这个异常,我发现这个使用CLOB在java抛出异常和接受的答案(使用setCharacterStream而不是setClob)为我工作

Copy/Pasted from the accepted answer (so all credits are for a_horse_with_no_name ) 从接受的答案复制/粘贴(因此所有学分都是针对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);

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. 我有一个特定的变体,需要从该数据库上运行的java代码中将clob插入Oracle数据库。 None of the answers here quite worked for me. 这里的答案都没有对我有用。

I eventually found solution, the trick being to use oracle.sql.CLOB 我最终找到了解决方案,诀窍是使用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; 

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. 我有一个PreparedStatement, stmt ,并使用stmt.setString(colIndex, value)来更新我的数据库,它有一个CLOB列。

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. 它似乎只发生在更新,而不是插入 - 当value null时,不确定为什么。 And I only ever had this occur with Oracle databases, not MSSQL or DB2. 而且我只在Oracle数据库中出现这种情况,而不是MSSQL或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! 这对我和其他人来说都是有效的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM