日期:2014-05-16 浏览次数:20350 次
package jdbc; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.io.Writer; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * * @author HaoWang */ public class ClobTest { public static void main(String[] args) { create(1,"C:\\a.txt"); read(1,"C:\\a_bak.txt"); } public static void create(int cid, String txtPath) { Connection conn = null; PreparedStatement ps = null; String sql = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sql = "insert into clob_test(cid,content) value(?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, cid); File file = new File(txtPath); Reader reader = new BufferedReader(new FileReader(file)); ps.setCharacterStream(2, reader, file.length()); int i = ps.executeUpdate(); System.out.println("i="+i); reader.close(); } catch (Exception ex) { System.out.println(ex.toString()); } finally { JdbcUtils.free(conn, ps, rs); } } public static void read(int cid, String txtPath) { Connection conn = null; PreparedStatement ps = null; String sql = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); sql = "Select content from clob_test where cid=?"; ps = conn.prepareStatement(sql); ps.setInt(1, cid); rs = ps.executeQuery(); while(rs.next()) { System.out.println(rs.getString(cid)); //直接获得文本内容 // Clob clob = rs.getClob(cid); // Reader reader = clob.getCharacterStream(); Reader reader = rs.getCharacterStream(cid); File file = new File(txtPath); Writer writer = new BufferedWriter(new FileWriter(file)); char[] buff = new char[1024]; for(int i=0; (i=reader.read(buff))>0;) { writer.write(buff, 0, i); } writer.close(); reader.close(); } } catch (Exception ex) { System.out.println(ex.toString()); } finally { JdbcUtils.free(conn, ps, rs); } } }
?