之前在学校的时候做的都是练习,小儿科,遇到的情况完全都在自己的设想范围内。最近老是遇到字段溢出的情况,但是varchar2好像最长也只有4000个字符。所以不得不另辟蹊径,就找上了clob字段。
package test;import java.io.BufferedReader;import java.io.IOException;import java.io.Writer;import java.sql.Clob;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import oracle.sql.CLOB;public class ClobTest { private static Connection conn; static { try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","wch","wch123"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) throws SQLException, IOException { // testInsert(); // testUpdate(); testRead(); } private static void testInsert() throws SQLException { String sql = "insert into CLOBTEST values(1, empty_clob(),empty_clob())"; Statement stm = conn.createStatement(); stm.execute(sql); } private static void testUpdate() throws SQLException, IOException { String sql = "select context,c2 from CLOBTEST where id = 1 for update"; Statement stm = conn.createStatement(); ResultSet rs = stm.executeQuery(sql); while (rs.next()) { oracle.sql.CLOB c = (CLOB) rs.getClob(1); Writer w = c.setCharacterStream(1); w.write("wchwchwch\r\n"); w.write("哈哈哈\r\n哈哈哈ds", 2, 5); w.flush(); w.close(); c = (CLOB) rs.getClob(2); w = c.setCharacterStream(1); w.write("dingsen"); w.flush(); w.close(); } conn.commit(); } private static void testRead() throws SQLException, IOException { String sql = "select context,c2 from CLOBTEST where id = 1"; PreparedStatement pstm = conn.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); System.out.println("-----------------------------------"); while (rs.next()) { Clob clob = rs.getClob(1); BufferedReader r = new BufferedReader(clob.getCharacterStream()); char[] cs = new char[10]; int total = 0; StringBuilder sb = new StringBuilder(); while ((total = r.read(cs)) != -1) { sb.append(cs,0,total); } System.out.println(sb.toString()); } } }