jdbctemplate的读写clob

所谓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();

//读取
在建立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();
这里使用FileCopyUtils的copy方法,将lobHandler取得的串流直接转接给文件输出FileWriter,FileOutputStream对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值