jdbctemplate的读写clob

来源:互联网 发布:cnc角度头编程 编辑:程序博客网 时间:2024/06/05 08:30

所谓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