码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2015-03-18 20:19:05      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:

数据库准备:

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     }

 

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

标签:

原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4348283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!