所谓CLOB 可以看成是文本文,所谓BLOB可以看成是图片文件
假设在mysql数据库上有以下表:
create
table
test(id
int
primary
key
,txt
TEXT
,
image
BLOB);
假设现在分别读取一个文字文件和二进制文件,并想将之存储到数据库中,则可以使用JdbcTemplate 如:
final
File binaryFile
=
new
File(
"
wish.jpg
"
);
final File txtFile = new File( " test.txt " );
final InputStream is = new FileInputStream(binaryFile);
final Reader reader = new FileReader(txtFile);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
final LobHandler lobHandler = new DefaultLobHandler();
jdbcTemplate.execute( " insert into test (txt,image) values (?,?) " ,
new AbstractLobCreatingPreparedStatementCallBack(lobHandler) {
protected void setValues(PreoparedStatement pstmt,LobCreator lobCreator){
lobCreator.setClobAsCharactoerStream(pstmt,1,reader,(int)textFile.length());
lobCreator.setBlobAsBinaryStream(pstmt,2,is,(int)binaryFile.length());
}
} );
reader.close();
is.close();
final File txtFile = new File( " test.txt " );
final InputStream is = new FileInputStream(binaryFile);
final Reader reader = new FileReader(txtFile);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
final LobHandler lobHandler = new DefaultLobHandler();
jdbcTemplate.execute( " insert into test (txt,image) values (?,?) " ,
new AbstractLobCreatingPreparedStatementCallBack(lobHandler) {
protected void setValues(PreoparedStatement pstmt,LobCreator lobCreator){
lobCreator.setClobAsCharactoerStream(pstmt,1,reader,(int)textFile.length());
lobCreator.setBlobAsBinaryStream(pstmt,2,is,(int)binaryFile.length());
}
} );
reader.close();
is.close();
在建立AbstractLobCreatingPreparedStatementCallBack对象时候,需要一个lobHandler实例, 对于一般的数据库,采用DefaultLobHandler足以,对于Oracle特定的lob处理,可以使用OracleLobHandler
如果是讲数据从数据库中读取出来并另存在未见,可以使用下面的程序
final
Writer writer
=
new
FileWriter(
"
test_back.txt
"
);
final OutputStream os = new FileOutputStream( new File( " wish_bak.jpg " ));
jdbcTemplate.query( " select txt,image from test where id=?,new AbstractLobStreamingResultSetExtractor(){
protected void streamData(ResultSet rs) throws SQLException,IOException,DataAccessException {
FileCopyUtils.copy(lobHandler.getClobAsCharacterStream(rs,1),writer);
FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs,2),os);
}
});
writer.close();
os.close();
final OutputStream os = new FileOutputStream( new File( " wish_bak.jpg " ));
jdbcTemplate.query( " select txt,image from test where id=?,new AbstractLobStreamingResultSetExtractor(){
protected void streamData(ResultSet rs) throws SQLException,IOException,DataAccessException {
FileCopyUtils.copy(lobHandler.getClobAsCharacterStream(rs,1),writer);
FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs,2),os);
}
});
writer.close();
os.close();
这里使用FileCopyUtils的copy方法,将lobHandler取得的串流直接转接给文件输出FileWriter,FileOutputStream对象