JDBC学习笔记(8):访问大段文本数据

数据库准备:

1 create table clob_test
2 (
3     id integer not null auto_increment,
4     big_text text not null,
5     primary key(id)
6 );

将大段文本添加进数据库:

 1 public static void create() throws SQLException, IOException {
 2         Connection conn = null;
 3         PreparedStatement ps = null;
 4         ResultSet rs = null;
 5         try {
 6             conn = JdbcUtils.getConnection();
 7             String sql = "insert into clob_test(big_text) values(?)";
 8             ps = conn.prepareStatement(sql);
 9             File file = new File("src/com/xxyh/jdbc/CRUD.java");
10             Reader reader = new BufferedReader(new FileReader(file));
11             
12             ps.setCharacterStream(1, reader, file.length());
13             int i = ps.executeUpdate();
14             reader.close();
15             System.out.println("i========" + i);
16         } finally {
17             JdbcUtils.close(rs, ps, conn);
18         }
19     }

从数据库中读取大段文本:

 1 public static void read() throws SQLException, IOException {
 2         Connection conn = null;
 3         Statement stmt  = null;
 4         ResultSet rs = null;
 5         
 6         try {
 7             conn = JdbcUtilsSingleton.getInstance().getConnection();
 8             stmt = conn.createStatement();
 9             String sql = "select big_text from clob_test";
10             rs = stmt.executeQuery(sql);
11             
12             while (rs.next()) {
13                 Clob clob = rs.getClob(1);
14                 Reader reader = clob.getCharacterStream();
15 //                reader = rs.getCharacterStream(1);
16                 File file = new File("CRUD_bak.java");
17                 Writer writer = new BufferedWriter(new FileWriter(file));
18                 char[] buffer = new char[1024];
19                 for (int i = 0; (i=reader.read(buffer)) > 0;) {
20                     writer.write(buffer, 0, i);
21                 }
22                 writer.close();
23                 reader.close();
24             }
25             
26         } finally {
27             JdbcUtilsSingleton.getInstance().close(rs, stmt, conn);
28         }
29     }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。