本文講述經過Spring的JdbcTemplate來讀寫數據庫大字段的實現方案,在一位網友的一篇博客的基礎上,查看api文檔整理而成。spring
1 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object 2 LobHandler lobHandler = new DefaultLobHandler(); // reusable object 3 4 jdbcTemplate.execute( 5 "INSERT INTO imagedb (image_name, content, description) VALUES (?, ?, ?)", 6 new AbstractLobCreatingPreparedStatementCallback(lobHandler) { 7 protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { 8 ps.setString(1, name); 9 lobCreator.setBlobAsBinaryStream(ps, 2, contentStream, contentLength); 10 lobCreator.setClobAsString(ps, 3, description); 11 } 12 } 13 );
如下內容不求精準,加入了本身的理解和猜想,勿做學術用。sql
LobCreator提供了多個接口來簡化大字段的寫入:對於BLOB,內容來源能夠是InputStream、byte[];對於CLOB,內容來源能夠是InputStream(自行確保都是ascii字符)、Reader、String。數據庫
1 JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object 2 final LobHandler lobHandler = new DefaultLobHandler(); // reusable object 3 4 jdbcTemplate.query( 5 "SELECT content FROM imagedb WHERE image_name=?", new Object[] {name}, 6 new AbstractLobStreamingResultSetExtractor() { 7 public void streamData(ResultSet rs) throws SQLException, IOException { 8 FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs, 1), contentStream); 9 } 10 } 11 );
上述實現僅僅針對一條記錄的讀取,若是要讀取多條記錄,須要注意ResultSet實例已經指向了第一條記錄(上述代碼也沒有調用rs.next()),可參考實現:api
1 public List<DFCL> batchRead(String sql, final String colNameFileName, 2 final String colNameFileContent) { 3 JdbcTemplate jt = JdbcService.getInstance().getJdbcTemplate(); 4 5 final LobHandler lobHandler = new DefaultLobHandler(); 6 final List<DFCL> dfclList = new ArrayList<DFCL>(); 7 jt.query(sql, new AbstractLobStreamingResultSetExtractor() { 8 protected void streamData(ResultSet rs) throws SQLException, 9 IOException, DataAccessException { 10 do{ //SINOBEST 文件下載 ,此處的rs初始化時已經指向第一條記錄 11 String name = rs.getString(colNameFileName); 12 String content = lobHandler.getClobAsString(rs, colNameFileContent); 13 14 DFCL cl = new DFCL(name, content); 15 dfclList.add(cl); 16 }while(rs.next()); 17 } 18 }); 19 return dfclList; 20 }
如下內容不求精準,加入了本身的理解和猜想,勿做學術用。工具
LobHandler提供了多個接口來簡化大字段的讀入:對於BLOB,能夠讀爲InputStream、byte[];對於CLOB,能夠讀爲InputStream、Reader、String。和LobCreator的寫入簡化是對應的。ui