所謂CLOB 可以看成是文本文,所謂BLOB可以看成是圖片檔案
假設在mysql資料庫上有以下表:
create table test(id int primary key,txt TEXT,image BLOB);
假設現在分別讀取一個文字檔案和二進位檔案,並想將之儲存到資料庫中,則可以使用JdbcTemplate 如:
final File binaryFile=new File("wish.jpg");<br />final File txtFile=new File("test.txt");<br />final InputStream is=new FileInputStream(binaryFile);<br />final Reader reader=new FileReader(txtFile);<br />JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);<br />final LobHandler lobHandler=new DefaultLobHandler();<br />jdbcTemplate.execute("insert into test (txt,image) values (?,?)",<br /> new AbstractLobCreatingPreparedStatementCallBack(lobHandler){<br /> protected void setValues(PreoparedStatement pstmt,LobCreator lobCreator){<br /> lobCreator.setClobAsCharactoerStream(pstmt,1,reader,(int)textFile.length());<br /> lobCreator.setBlobAsBinaryStream(pstmt,2,is,(int)binaryFile.length());<br /> }<br /> });<br />reader.close();<br />is.close();
在建立AbstractLobCreatingPreparedStatementCallBack對象時候,需要一個lobHandler執行個體, 對於一般的資料庫,採用DefaultLobHandler足以,對於Oracle特定的lob處理,可以使用OracleLobHandler
如果是講資料從資料庫中讀取出來並另存在未見,可以使用下面的程式
final Writer writer=new FileWriter("test_back.txt");<br />final OutputStream os=new FileOutputStream(new File("wish_bak.jpg"));<br />jdbcTemplate.query("select txt,image from test where id=?,new AbstractLobStreamingResultSetExtractor(){<br /> protected void streamData(ResultSet rs) throws SQLException,IOException,DataAccessException{<br /> FileCopyUtils.copy(lobHandler.getClobAsCharacterStream(rs,1),writer);<br /> FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs,2),os);<br /> }<br /> });<br />writer.close();<br />os.close();
這裡使用FileCopyUtils的copy方法,將lobHandler取得的串流直接轉接給檔案輸出FileWriter,FileOutputStream對象