有个表是这样的:
create table emp430_1( id number(12), name nvarchar2(20), profile clob, primary key(id) );
其中profile为clob类型,这种类型可以容纳超大文本。
以下是从中连续读取数据的程序:
package com.hy.lab.clob; import java.io.Reader; import java.sql.*; import java.util.ArrayList; import java.util.List; public class ClobReader { //-- 以下为连接Oracle数据库的四大参数 private static final String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl"; private static final String USER = "luna"; private static final String PSWD = "1234"; public static void main(String[] args){ List<Emp> ls=new ArrayList<>(); ls.add(new Emp(1,"武松","双刀客")); ls.add(new Emp(2,"李逵","双斧头客")); ls.add(new Emp(3,"董平","双枪将")); ls.add(new Emp(4,"鲁达","扁铲发明者")); Connection conn = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, USER, PSWD); conn.setAutoCommit(false); String sql="select * from emp430_1"; pstmt = conn.prepareStatement(sql); ResultSet rs=pstmt.executeQuery(); while(rs.next()){ long id=rs.getLong("id"); String name=rs.getString("name"); Clob clob=rs.getClob("profile"); String profile=extractTxtFrom(clob); System.out.println(String.format("Emp id=%d name=%s profile=%s",id,name,profile)); } rs.close(); System.out.println("完成读取"); } catch (Exception e) { e.printStackTrace(); } finally { try { pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } private static String extractTxtFrom(Clob clob) throws Exception{ Reader reader=clob.getCharacterStream(); char[] arr=new char[1024]; int length=reader.read(arr); StringBuilder sb=new StringBuilder(); while(length!=-1){ String part=new String(arr,0,length); sb.append(part); length=reader.read(arr); } return sb.toString(); } }
END