How do I store a string longer than 4000 characters in an Oracle Database using Java/JDBC?

无人久伴 提交于 2019-11-27 15:23:50

You have (at least) two options:

  • use connection.createClob() to create a Clob, set the data on it, and set it on the prepared statement. This will work for smaller data

  • use preparedStatement.setClob(position, reader) - here you will have a Reader instance.

Here is an example at oracle.com for using LOB columns with Oracle and JDBC. Basically, it's inserting a LOB locator for an empty LOB (actually two, since it's demonstrating both BLOBs and CLOBs), locking the row for update, and then using the BLOB and CLOB OutputStream interfaces to write the data into the LOBs. When the "SELECT ... FOR UPDATE" is released, the LOBs will be refreshed in the database and the newly inserted data will be visible.

Also, this below solution explains how to handle this using PL/SQL

Reference: http://gogates.blogspot.com/2013/09/inserting-clob-data-which-is-more-than.html


Inserting CLOB data which is more than 4000 characters into Oracle Table I was trying to insert 4000+ characters data into an Oracle table having CLOB as data type, but could not do that.. using simple insert statement

Table Structure which I used is as below

CREATE TABLE ClobTest (id number, clobData clob );

Table structure is pretty simple, having only 2 columns a number and a clob data type.

Now... if you run below query it will get execute without any error

INSERT INTO ClobTest VALUES(1, 'ClobTestData');

However, when you increase the length of your data set 4000+ it will not succeed.and will give error as below

Error report: SQL Error: ORA-01704: string literal too long 01704. 00000 - "string literal too long" *Cause: The string literal is longer than 4000 characters. *Action: Use a string literal of at most 4000 characters. Longer values may only be entered using bind variables.

After googling this issue, came to know that, if you want to insert 4000+ char data into CLOB data type, try to do that using PL-SQL block.

Root cause of this is, Oracle SQL do not support char / varchar data type which is more than 4000 characters; however PL-SQL does so.

I used below anonymous pl-sql to insert 4000+ character data into CLOB data type

DECLARE

vClob VARCHAR(8000);

BEGIN

vClob := '<Charater data having 4000+ characters>';

INSERT INTO ClobTest VALUES(1, vClob);

END;

To verify if really 4000+ characters got inserted into target executed below query

SELECT LENGHT(clobData) FROM ClobTest 

I hope that helps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!