使用Spring JdbcTemplate实现CLOB和BLOB的存取

所谓CLOB 可以看成是文本文,所谓BLOB可以看成是图片文件
假设在mysql数据库上有以下表:
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifJdbcTemplate实现CLOB和BLOB的存取" />create table test(id int primary key,txt TEXT,image BLOB);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifJdbcTemplate实现CLOB和BLOB的存取" />
[java] view
plain copy
print ?
-
final
File newbinaryFile= File( "wish.jpg"); -
final
File newtxtFile= File( "test.txt"); -
final
InputStream newis= FileInputStream(binaryFile); -
final
Reader newreader= FileReader(txtFile); -
JdbcTemplate
jdbcTemplate=new JdbcTemplate(dataSource); -
final
LobHandler newlobHandler= DefaultLobHandler(); -
jdbcTemplate.execute("insert
into ,test (txt,image) values (?,?)" -
new AbstractLobCreatingPrepa redStatementCallBack(lobHandler){ -
protected void setValues(PreoparedStatement pstmt,LobCreator lobCreator){ -
lobCreator.setClobAsCharactoerStrea m(pstmt,1,reader,(int)textFile.length()); -
lobCreator.setBlobAsBinaryStream(pstmt,2,is,(int)binaryFile.length()); -
} -
}); -
reader.close();
-
is.close();
在建立AbstractLobCreatingPrepa
如果是讲数据从数据库中读取出来并另存在未见,可以使用下面的程序
[c-sharp] view
plain copy
print ?
-
final
Writer newwriter= FileWriter( "test_back.txt"); -
final
OutputStream os=new FileOutputStream( newFile( "wish_bak.jpg")); -
jdbcTemplate.query("select
txt,image from test where id=?,new AbstractLobStreamingResu ltSetExtractor(){ -
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对象