Clob转换为String的三种方法:
使用Clob对象的getSubString(long , int)方法使用字节流读取使用字符流读取代码如下:
Clob clob = resultSet.getClob(1); //第一种转换方法 使用Clob的getSubString(long , int)方法 if(clob!= null){ String clobString = clob.getSubString(1L,(int)clob.length()); System.out.println(clobString); } //第二种转换方法,使用字节流读取 if(clob!= null){ InputStream input = clob.getAsciiStream(); int length = (int)clob.length(); String str = ""; byte [] bb = new byte[length]; try { int result = input.read(bb); if(result!= -1) str = new String(bb); System.out.println(str); } catch (IOException e) { e.printStackTrace(); } } //第三种方法,使用字符流读取 if(clob != null){ Reader reader = clob.getCharacterStream(); BufferedReader bufferedReader = new BufferedReader(reader); String result = ""; String str = ""; try { while((str = bufferedReader.readLine()) != null){ result += (str + "\n"); } System.out.println(result); } catch (IOException e) { e.printStackTrace(); } }备注:需要ojdbc4.jar,如果针对于jdk1.6的话则最好是用ojdbc6.jar
clob字段不能直接插入 插入clob类型的字段需要如下几个步骤
取消连接的自动提交针对clob字段,插入一个占位符,即插入empty_clob查询要记录,一定要是for update的获取clob字段 ,把获取的java.sql.Clob强制转换为oracle.sql.Clob获取oralce.sql.Clob对象的流通过该流,把字符串写到数据库中取代码如下(用的是dbutils):
插入的方法如下:
/** * 数据库中插入Clob类型字段 */ public void insertClob(){ String sql = "insert into esb.esb_exception_manage_ (id_ , app_name , flow_name , root_ , detail_ , status_code_) values('218949957478440256' , 'app_name' , 'flow_name' , 'root' , empty_clob() ,1)"; QueryRunner qr = new QueryRunner(); getConnection(); try { conn.setAutoCommit(false); int result = qr.update(conn , sql); String sql_clob = "select * from esb.esb_exception_manage_ where id_ = ? for update "; ResultSetClobHandle resultSetClobHandle = new ResultSetClobHandle(); int result2 = qr.query(conn , sql_clob , resultSetClobHandle , "258949957478240256"); conn.commit(); } catch (SQLException e) { e.printStackTrace(); } }ResultSetHandle的实现类如下:
private class ResultSetClobHandle implements ResultSetHandler<Integer>{ @Override public Integer handle(ResultSet resultSet) throws SQLException { if(resultSet.next()){ oracle.sql.CLOB clob = (oracle.sql.CLOB)resultSet.getClob("detail_"); Writer writer = clob.getCharacterOutputStream(); // 获取Clob对象的流 String str = "it is a big string!"; try { writer.write(str); //把字符串写入到数据库的clob对象中 writer.flush(); } catch (IOException e) { e.printStackTrace(); } } return 1; } }转载于:https://www.cnblogs.com/jinxiuze/p/8039168.html
