Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to insert CLOB into oracle database

I need to write an XML file content into oracle database where the column is of CLOB datatype. How will I do that?

like image 280
Ianthe Avatar asked Apr 05 '11 08:04

Ianthe


People also ask

How do I add a CLOB column in Oracle?

Type an "ALTER TABLE" command to add a CLOB item to an existing table, using the following SQL code as a guide: ALTER TABLE your_table ( add big_text_field CLOB ); Press "Enter" to execute the command. Here, "your_table" is the name of a database table to which you want a CLOB field added.

How do you insert a CLOB file?

For inserting CLOB data using SQL Developer (in my case), you can do something like this: INSERT INTO mytable VALUES('REQUEST2',:a,NULL); Writing :a will result in a window popping up for you to enter value for parameter :a. Just write all your '{"customer"asxcbasjbab....:}' in the window that popped up.


8 Answers

The easiest way is to simply use the

stmt.setString(position, xml);

methods (for "small" strings which can be easily kept in Java memory), or

try {
  java.sql.Clob clob = 
    oracle.sql.CLOB.createTemporary(
      connection, false, oracle.sql.CLOB.DURATION_SESSION);

  clob.setString(1, xml);
  stmt.setClob(position, clob);
  stmt.execute();
}

// Important!
finally {
  clob.free();
}
like image 105
Lukas Eder Avatar answered Oct 25 '22 15:10

Lukas Eder


OUTDATED See Lukas Eder's answer below.

With about 100 lines of code ;-) Here is an example.

The main point: Unlike with other JDBC drivers, the one from Oracle doesn't support using Reader and InputStream as parameters of an INSERT. Instead, you must SELECT the CLOB column FOR UPDATE and then write into the ResultSet

I suggest that you move this code into a helper method/class. Otherwise, it will pollute the rest of your code.

like image 26
Aaron Digulla Avatar answered Oct 25 '22 17:10

Aaron Digulla


passing the xml content as string.

table1 

ID   int
XML  CLOB



import oracle.jdbc.OraclePreparedStatement;
/*
Your Code
*/
 void insert(int id, String xml){
    try {
        String sql = "INSERT INTO table1(ID,XML) VALUES ("
                + id
                + "', ? )";
        PreparedStatement ps = conn.prepareStatement(sql);
        ((OraclePreparedStatement) ps).setStringForClob(1, xml);
        ps.execute();
        result = true;
        } catch (Exception e) {
        e.printStackTrace();
    }
  }
like image 29
Vignesh Avatar answered Oct 25 '22 15:10

Vignesh


This code worked for me. I use ojdbc6-11.2.0.2.jar.

java.sql.Connection con;
javax.xml.bind.Marshaller marshaller;

Clob xmlClob = con.createClob();
try {
  try (Writer xmlClobWriter = xmlClob.setCharacterStream(1)) {
    m.marshal(jaxbObject, xmlClobWriter);
  } // xmlClobWriter.close();
  try (PreparedStatement stmt = con.prepareStatement("INSERT INTO table (xml) values(?)")) {
    stmt.setClob(1, xmlClob);
    stmt.executeUpdate();
  }
} finally {
  xmlClob.free();
}
like image 32
TomWolk Avatar answered Oct 25 '22 17:10

TomWolk


Converting clob to string:

Clob clob=rs.getClob(2);      
String str=(String)clob.getSubString(1,(int)clob.length());      
System.out.println("Clob Data is : "+str);
like image 25
Ramesh Avatar answered Oct 25 '22 17:10

Ramesh


For this purpose you need to make the connection result set

ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE

Connection con=null;
//initialize connection variable to connect to your database...
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String query="Select MYCLOB from TABLE_NAME for update";
con.setAutoCommit(false);
ResultSet resultset=stmt.executeQuery(query);


if(resultset.next()){
oracle.sql.CLOB    clobnew = ((OracleResultSet) rss).getCLOB("MYCLOB");
PrintWriter pw = new PrintWriter(clobnew.getCharacterOutputStream() );
BufferedReader br = new BufferedReader( new FileReader( new File("filename.xml") ) );
String  lineIn = null;
while( ( lineIn = br.readLine() ) != null )
      pw.println( lineIn );
      pw.close();
      br.close();
}

con.setAutoCommit(true);
con.commit();
}

Note: its important that you add the phrase for update at the end of the query that is written to select the row...

Follow the above code to insert the XML file

like image 31
Sangeet Menon Avatar answered Oct 25 '22 15:10

Sangeet Menon


You can very well do it with below code, i am giving you just the code to insert xml hope u are done with rest of other things..

import oracle.xdb.XMLType;

//now inside the class......
// this will be to convert xml into string

File file = new File(your file path);
FileReader fileR = new FileReader(file);
fileR.read(data);
String str = new String(data);

// now to enter it into db

conn = DriverManager.getConnection(serverName, userId, password);

XMLType objXml = XMLType.createXML(conn, str);

// inside the query statement put this code

objPreparedstatmnt.setObject(your value index, objXml);

I have done like this and it is working fine.

like image 39
Shantanu Avatar answered Oct 25 '22 16:10

Shantanu


I had similar issue. Changed one of my table column from varchar2 to CLOB. I didn't needed to change any java code. I kept it as setString(..) only so no need to change set method as setClob() etch if you are using following versions ATLEAST of Oracle and jdbc driver.

I tried in In Oracle 11g and driver ojdbc6-11.2.0.4.jar

like image 34
Mandrake Avatar answered Oct 25 '22 15:10

Mandrake