一、LOB(Large Objects)大對象,是用來存儲大量的二進制和文本數據的一種數據類型(一個LOB字段可存儲多達4GB的數據)sql
--LOB分類兩種類型:1)內部LOB; 2)外部LOB:數據庫
--內部LOB將數據已字節流的形式存儲在數據庫的內部。於是,內部LOB的許多操做均可以參與事務,也能夠像處理普通數據同樣對其進行備份和恢復操做;spa
--Oracle支持三種類型的內部LOB:1)BLOB(二進制數據);2)CLOB(單字節字符數據);3)NCLOB(多字節字符數據);操作系統
--CLOB和NCLOB類型適用於存儲超長的文本數據,BLOB字段適用於存儲大量的二進制數據,如圖像、視頻、文件等。code
--外部LOB:目前只支持一種外部LOB類型,即BFILE類型,該類型僅存儲數據在操做系統中的位置信息,而數據的實體之外部文件的形式存在於文件系統中。視頻
--BFILE類型所表示的數據都是隻讀的,不參與事務。該類型可幫助用戶管理大量的由外部程序訪問的文件。對象
二、使用JDBC向數據庫插入BLOB類型的數據時必須使用PreparedStatement。blog
三、向Oracle數據庫插入Blob類型數據事務
public void insertBlobData(){ Connection conn = null; PreparedStatement ps = null; String sql = "INSERT INTO customers(id, name, picture) VALUES(?,?,?)"; try{ conn = JDBCUtils.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, 12345); ps.setString(2, "Alice"); InputStream in = new FileInputStream("test.jpg"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len; while((len = in.read(b)) != -1){ baos.write(b, 0, len); } ps.setBytes(3, baos.toByteArray()); ps.executeUpdate(); in.close(); }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.release(conn, ps, null); } }
四、從Oracle數據庫中讀取Blob類型的數據並經過IO流寫入文件中:get
public void readBlobData(){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String sql = "SELECT id, name, picture FROM customers WHERE id = ?"; try{ conn = JDBCUtils.getConnection(); ps = conn.prepareStatement(sql); ps.setInt(1, 12345); rs = ps.executeQuery(); if(rs.next()){ Blob blob = rs.getBlob(3); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("out.jpg")); InputStream in = blob.getBinaryStream(); byte[] b = new byte[1024]; int len; while((len = in.read(b)) != -1){ bos.write(b,0, len); bos.flush(); } bos.close(); in.close(); } }catch(Exception e){ e.printStackTrace(); }finally{ JDBCUtils.release(conn, ps, rs); } }