讲解Oracle中的Clob与String类型转换
讲解Oracle中的Clob与String类型转换
在论坛上看到的一个问题,其实我从来没有用过Clob,因为确实没这个需求,但是为了抢分,如何最快的找到解决方案呢,第一时间想到spring,因为spring对orm工具有封装, 像ibatis,hibernate等,在spring.jar中大概翻了一下包,根据包名和类名发现如下可疑类org.springframework.orm.ibatis.support.ClobStringTypeHandler 根据源码跟踪到了 org.springframework.jdbc.support.lob.OracleLobHandler 这个类才是内有乾坤,有我想要的一切东西,嘿嘿,不好意思了,统统抄来.
在spring包中有个org.springframework.jdbc.support.lob.AbstractLobHandler这里面定义了基本的Clob和Blog处理方法
org.springframework.jdbc.support.lob.DefaultLobHandler是默认的实现,除了Oracle其他数据库使用此实现
org.springframework.jdbc.support.lob.OracleLobHandler是专门用于Oracle的实现,可见Oracle的BT,为了不造成直接包依赖,相关的调用都是利用反射完成的.有兴趣的朋友可以去阅读下这两个类,以便了解Oracle的特殊性.
经过分析,将Clob的创建,以及与String的互转代码放出来供大家使用.当然不可能完全copy了,我做了些简化处理,不过已经测试了,没用问题.更多细节请查阅spring的org.springframework.jdbc.support.lob包源码.
来源:(http://blog.sina.com.cn/s/blog_5109612b0100aq6l.html) - Oracle中的Clob与String类型转换_镭射头_新浪博客
SqlUtil类是我为了方便测试写的,大家靠代码就能够猜出来其内容了,所以就不全贴了,只贴本文的主题部分.
public static Object createOracleLob(Connection conn, String lobClassName) throws Exception { Class lobClass = conn.getClass().getClassLoader().loadClass( lobClassName); final Integer DURATION_SESSION = new Integer(lobClass.getField( ”DURATION_SESSION”).getInt(null)); final Integer MODE_READWRITE = new Integer(lobClass.getField( ”MODE_READWRITE”).getInt(null)); Method createTemporary = lobClass.getMethod(”createTemporary”, new Class[] { Connection.class, boolean.class, int.class }); Object lob = createTemporary.invoke(null, new Object[] { conn, false, DURATION_SESSION }); Method open = lobClass.getMethod(”open”, new Class[] { int.class }); open.invoke(lob, new Object[] { MODE_READWRITE }); return lob; } public static String oracleClob2Str(Clob clob) throws Exception { return (clob != null ? clob.getSubString(1, (int) clob.length()) : null); } public static Clob oracleStr2Clob(String str, Clob lob) throws Exception { Method methodToInvoke = lob.getClass().getMethod( ”getCharacterOutputStream”, (Class[]) null); Writer writer = (Writer) methodToInvoke.invoke(lob, (Object[]) null); writer.write(str); writer.close(); return lob; } public static void main(String[] args) throws Exception { //创建数据源略 Connection conn = SqlUtil.getConnection(); Clob clob = (Clob) createOracleLob(conn, ”oracle.sql.CLOB”);// BLOB的话传oracle.sql.BLOB // create table testTb (TheClob Clob); PreparedStatement pstmt = conn .prepareStatement(”insert into testTb (TheClob) values (?)”); pstmt.setClob(1, oracleStr2Clob(”test”, clob)); pstmt.execute(); SqlUtil.closeStmt(pstmt); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(”select * from testTb”); while (rs.next()) { String str = oracleClob2Str(rs.getClob(1)); System.out.println(str); } SqlUtil.closeRs(rs); SqlUtil.closeStmt(stmt); SqlUtil.closeConn(conn); } |
评论暂时关闭