ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.Reader;ImportJava.io.StringReader;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;ImportOracle.jdbc.OracleDriver;ImportOracle.sql.CLOB; Public classclobtest {String URL= "JDBC:ORACLE:THIN:@127.0.0.1:1521:ORCL"; String User= "His_xs"; String pwd= "123456"; String text= "This is the data to be inserted into the CLOB"; Private voidClobimport ()throwsClassNotFoundException, SQLException {//TODO auto-generated Method StubDrivermanager.registerdriver (Neworacledriver ()); Connection Conn= drivermanager.getconnection (URL, user, pwd);//Get the Connection objectString sql = "INSERT into Clob_test (ID,STR) VALUES (' 1 ',?)";//the SQL statement to executePreparedStatement stmt= conn.preparestatement (SQL);//Load SQL statements//preparedstatement Support SQL with question mark? , can be dynamically replaced? The content. Reader Clobreader =NewStringReader (text);//turn text into a stream formStmt.setcharacterstream (1, Clobreader, Text.length ());//Replace in SQL statement? intnum = Stmt.executeupdate ();//Execute SQL if(num > 0) {System.out.println ("OK"); } Else{System.out.println ("NO"); } stmt.close (); Conn.close (); } //Convert a character clob to a string type PublicString clobtostring (CLOB CLOB)throwsSQLException, IOException {String restring= ""; Reader is= Clob.getcharacterstream ();//Get the FlowBufferedReader br =NewBufferedReader (IS); String s=Br.readline (); StringBuffer SB=NewStringBuffer (); while(s! =NULL) {//the execution loop takes all the strings out and pays the value to StringBuffer from StringBuffer to stringSb.append (s); S=Br.readline (); } restring=sb.tostring (); returnrestring; } Private voidClobexport ()throwsclassnotfoundexception, SQLException, IOException {//TODO auto-generated Method StubCLOB CLOB =NULL; String SQL= "SELECT * from Clob_test where id=1"; Drivermanager.registerdriver (Neworacledriver ()); Connection Conn= drivermanager.getconnection (URL, user, pwd);//Get the Connection objectPreparedStatement stmt =conn.preparestatement (SQL); ResultSet RS=Stmt.executequery (); String ID= ""; String content= ""; if(Rs.next ()) {ID= rs.getstring ("id");//Get IDCLOB = (Oracle.sql.CLOB) rs.getclob ("str");//get clob field str//Note: The data is not available with rs.getstring ("str") and NULL is returned;Content =clobtostring (CLOB); } stmt.close (); Conn.close (); //Output ResultsSystem.out.println (ID); SYSTEM.OUT.PRINTLN (content); } Public Static voidMain (string[] args)throwsException {Clobtest a=Newclobtest (); A.clobimport (); A.clobexport (); }}
A practical way to store and read Oracle CLOB type fields in Java