Java/JSP Oracle中的大欄位存二進位/大文本

來源:互聯網
上載者:User

資料庫中提供了兩種欄位類型 Blob 和 Clob 用於儲存大型字串或位元據(片)。

Blob 採用單位元組儲存,適合儲存位元據,片檔案。
Clob 採用多位元組儲存,適合儲存大型文本資料。

Oracle中處理BLOB/CLOB欄位的方式比較特別,所以需要特別注意下面兩點:

1. 在Oracle JDBC中採用流機制對 BLOB/CLOB 進行讀寫操作,所以要注意不能在批處理中讀寫 BLOB/CLOB欄位,否則將出現
Stream type cannot be used in batching 異常。

2. Oracle BLOB/CLOB 欄位本身擁有一個遊標(cursor),JDBC通過遊標對Blob/Clob欄位進行操作,在Blob/Clob欄位建立之前,無法擷取其遊標控制代碼,會出現
Connection reset by peer: socket write error 異常。

正確的做法是:首先建立一個空 Blob/Clob 欄位,再從這個空 Blob/Clob欄位擷取遊標,例如下面的代碼:

PreparedStatement ps = conn.prepareStatement( " insert into PICTURE(image,resume) values(?,?) " );
// 通過oralce.sql.BLOB/CLOB.empty_lob()構造空Blob/Clob對象
ps.setBlob( 1 ,oracle.sql.BLOB.empty_lob());
ps.setClob( 2 ,oracle.sql.CLOB.empty_lob());

ps.excuteUpdate();
ps.close();

// 再次對讀出Blob/Clob控制代碼
ps = conn.prepareStatement( " select image,resume from PICTURE where id=? for update " );
ps.setInt( 1 , 100 );

ResultSet rs = ps.executeQuery();
rs.next();

oracle.sql.BLOB imgBlob = (oracle.sql.BLOB)rs.getBlob( 1 );
oracle.sql.CLOB resClob = (oracle.sql.CLOB)rs.getClob( 2 );

// 將位元據寫入Blob
FileInputStream inStream =   new FileInputStream( " c://image.jpg " );
OutputStream outStream = imgBlob.getBinaryOutputStream();

byte [] buf =   new   byte [ 10240 ];
int len;
while (len = inStream.read(buf) > 0 ) {
outStream.write(buf, 0 ,len);
}
inStream.close();
outStream.cloese();

// 將字串寫入Clob
resClob.putString( 1 , " this is a clob " );

// 再將Blob/Clob欄位更新到資料庫
ps = conn.prepareStatement( " update PICTURE set image=? and resume=? where id=? " );
ps.setBlob( 1 ,imgBlob);
ps.setClob( 2 ,resClob);
ps.setInt( 3 , 100 );

ps.executeUpdate();
ps.close();

 

聯繫我們

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