在Java中使用Oracle blob

來源:互聯網
上載者:User
oracle Oracle中的lob (Large Object)可以儲存非常大的資料(可能是4GB),這樣就可以通過將檔案或其它任何對象序列化成位元組輸出資料流(OutputStream)後寫入資料庫,之後使用位元組輸入資料流(InputStream)將資料讀出然後還原序列化為原始檔案或對象。操作時需要使用oracle的JDBC包,它擴充了sun的JDBC包中的Blob對象。同時需要注意一些細節。下面的代碼示範如何使用blob(執行個體中需要Oracle的JDBC包)。

import oracle.jdbc.OracleResultSet; // 使用Oracle的ResultSet對象
import oracle.sql.BLOB; // 使用Oracle的BLOB對象,而不是sun的Blob

...

try{
Connection conn=<資料庫連接>;
File file=<存入資料庫的檔案對象>;
conn.setAutoCommit(false); // 取消Connection對象的auto commit屬性
String file_name=file.getName();

// 資料庫中有一個item表,其中的file_name (varchar2)隱藏檔名,file_blob (blob)隱藏檔對象
String sql="INSERT INTO item (file_name,file_blob) VALUES ('" + file_name + "',EMPTY_BLOB())"; // 使用“EMPTY_BLOB()“成生一個空blob
Statement stmt=conn.createStatement();
int count=stmt.executeUpdate(sql);

sql="SELECT file_blob FROM item WHERE iid='" + iid + "' FOR UPDATE"; // 使用“FOR UPDATE”得到表的寫鎖
ResultSet rs=stmt.executeQuery(sql);
rs.next();
BLOB blob=((OracleResultSet)rs).getBLOB("file_blob"); // 得到BLOB對象
OutputStream out=blob.getBinaryOutputStream(); // 建立輸出資料流
InputStream in=new FileInputStream(file); // 建立輸入資料流
int size=blob.getBufferSize();
byte[] buffer=new byte[size]; // 建立緩衝區
int len;
while((len=in.read(buffer)) != -1)
out.write(buffer,0,len);
in.close();
out.close();

conn.commit();
}
catch(Exception ex){
try{
conn.rollback();
}
catch(SQLException sqle){
System.err.println(sqle.getMessage());
}
}

如果要讀出檔案的話只需調用BLOB的getBinaryStream()產生一個輸入資料流,再寫入一個檔案就行了。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.