使用Spring JdbcTemplate實現CLOB和BLOB的存取

來源:互聯網
上載者:User

所謂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對象

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.