串流資料型別
(史帝芬, idealist@gcn.net.tw, 2003/10/04)
不知道有沒有遇到和我一樣的問題,我希望將圖檔存到資料庫中,怎麼存? 我發現在Oracle 9.2中一有種資料型別叫BLOB可以存檔案,它最大可儲存4GB,蠻大的,絕大部份情況都夠用才對吧?!! 接下來要解決的問題是,程式中如何存取BLOB型別的欄位? 傳統的setXXX和getXXX仍然可以用! 但是如果檔案較大時,效率會很差,比較好的作法是以串流的方式來存取,這就是本篇文章要介紹的方法。在Java中提供了java.sql.Blob介面給資料庫實作,oracle.sql.BLOB類別即實作此介面,用來保存BLOB指位器。 BLOB指位器使得程式可以用串流的方式來操作串流資料型別的欄位。接下來我將以幾個範例程式作說明。程式中建立Connection的方式直接使用 Connection Pool所建立的類別,各位網友從變數名稱就可以看出來,並不需要先了解Connection Pool如何建立。
範例程式使用的Table如下,Table name為game_today_sell。
欄位名 | 型別 | 說明 |
---|---|---|
name | VARCHAR2(20) | 圖片名 |
picture | BLOB | 圖檔 |
description | VARCHAR2(100) | 圖片說明 |
- INSERT
ConnectionPool pool = ConnectionPool.getIstance();
Connection con = pool.getConnection();
Statement stmt = con.createStatement();
String sql = "insert into game_today_sell(name, picture, description) "
+ "values('picture01', empty_blob(), 'myDescription01') "; //說明A
stmt.execute(sql);
stmt.close();
//取得圖檔欄位的指位器
stmt = con.createStatement();
sql = "select picture from game_today_sell where name = 'picture01' for update nowait "; //說明B
ResultSet rs = stmt.executeQuery(sql);
rs.next();
BLOB blob = (BLOB) rs.getBlob(1); //說明C
rs.close();
rs = null;
//將圖檔存入資料庫
OutputStream out = blob.getBinaryOutputStream();
out.write(buffer); //buffer為byte[],是經由InputStream讀入的檔案
out.close();
out = null;
con.commit();
說明:
A. empty_blob()是用來在插入資料列時,同一時間建立一個指址器,指向BLOB欄位。
B. 取得指位器時可以用 for update nowait 或 for update ,兩者的差別在於當該資料列被鎖定時,有加nowait的會立刻返回,並產生exception,沒有加nowait的會等到資料列解鎖。
C. 當取得指位器後,需轉型成資料庫提供的型別。 - SELECT
Blob picture = null;
String sql = null;
Connection con = pool.getConnection();
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
sql = "select * from game_today_sell where name = 'picture01'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
picture = rs.getBlob(2); //picture為第二個欄位
filename = rs.getString("filename");
}
InputStream is = picture.getBinaryStream();
int length = (int) picture.length();
byte[] buffer = new byte[length];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close(); - UPDATE
看完Insert、Select後,應該會想知道怎麼update吧? 如下sql...
update game_today_sell
set picture = ?
where name = 'picture'
然後用PreparedStatement執行...
pstmt.setBinaryStream(is) 或 pstmt.setBytes(buffer) - DELETE
如果只想單獨刪除picture中的值,而不是刪除整個資料列的話,也蠻簡單的,只要將指位器設為NULL,如下:
update game_today_sell
set picture = empty_blob()
where name = 'picture01'
當這個UPDATE被執行時,新的BLOB指位器將取代原有的指位器,於是BLOB就被設為NULL了。