JAVA代码如何读取、写入、更新CLOB字段呢?
下文笔者讲述使用Java代码读取,写入,更新CLOB字段的方法分享,如下所示
例:
例:
建表
create table t_clob( id varchar2(32) primary key, clobfield CLOB );
/** * 读取CLOB字段的代码示例 */ public void readClob() { //自定义的数据库连接管理类 Connection conn = DbManager.getInstance().getConnection(); try { PreparedStatement stat = conn .prepareStatement("select clobfield from t_clob where id='1'"); ResultSet rs = stat.executeQuery(); if (rs.next()) { oracle.sql.CLOB clob = (oracle.sql.CLOB) rs .getClob("clobfield"); String value = clob.getSubString(1, (int) clob.length()); System.out.println("CLOB字段的值:" + value); } conn.commit(); } catch (SQLException e) { e.printStackTrace(); } DbManager.getInstance().closeConnection(conn); } /** * 写入、更新CLOB字段的代码示例 */ public void writeClob() { //自定义的数据库连接管理类 Connection conn = DbManager.getInstance().getConnection(); try { conn.setAutoCommit(false); PreparedStatement stat = conn .prepareStatement("insert into t_clob (id,clobfield) values(sys_guid(),?)"); String clobContent = "This is a very very long string"; StringReader reader = new StringReader(clobContent); stat.setCharacterStream(1, reader, clobContent.length()); stat.executeUpdate(); stat = conn .prepareStatement("select clobfield from t_clob where id='1' for update"); ResultSet rs = stat.executeQuery(); if (rs.next()) { oracle.sql.CLOB clob = (oracle.sql.CLOB) rs .getClob("clobfield"); Writer outStream = clob.getCharacterOutputStream(); char[] c = clobContent.toCharArray(); outStream.write(c, 0, c.length); outStream.flush(); outStream.close(); } conn.commit(); } catch (SQLException | IOException e) { e.printStackTrace(); } DbManager.getInstance().closeConnection(conn); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。