Java 存取Blob、Clob資料。

來源:互聯網
上載者:User
JDBC 2.0中提供了對SQL3標準中引入的新的資料類型,如Blob(binary large object)、Clob(character large object)、Array 對象、REF(對象參考,object reference)和 UDT(使用者定義資料類型,user-defined datatype)等的支援。這些新的資料類型結合在一起,使得資料庫設計人員可以建立更豐富的模式,並簡化了對複雜資料的處理和持久化。

  例如,我們要向tbl_User表中插入使用者的照片,這時就可以使用流將Blob對象匯入資料庫中:

String sql = "intsert into tbl_User values(?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql) ;

File file = new File("C:/images/photo.jpg") ;
FileInputStream fis = new FileInputStream(file);

pstmt.setString(1, "John");
pstmt.setBinaryStream(2, fis, (int)file.length());

pstmt.executeUpdate();

pstmt.close();
fis.close();

  其中SQL語句的第一個參數為使用者名稱,第二個參數為photo,它是一個Blob型對象。這樣在將資料插入資料庫之後,我們就可以用程式擷取該資料了:

String sql = "select photo from tbl_User where username = ?";
PreparedStatement pstmt = con.prepareStatement(selectSQL) ;

pstmt.setString(1, "John");
ResultSet rs = pstmt.executeQuery() ;

rs.next();
Blob blob = rs.getBlob("photo") ;

ImageIcon icon = new ImageIcon(blob.getBytes(1, (int)blob.length())) ;
JLabel photo = new JLabel(icon);

rs.close();
pstmt.close();

  類似地,我們也可以對Clob對象進行相應的操作。下面是一個從 ASCII 流中直接將 Clob對象插入資料庫中的例子:

String sql = "insert into tbl_Articles values(?,?)";
PreparedStatement pstmt = con.prepareStatement(sql) ;

File file = new File("C:/data/news.txt") ;
FileInputStream fis = new FileInputStream(file);

pstmt.setString(1, "Iraq War");
pstmt.setAsciiStream(2, fis, (int)file.length());

pstmt.executeUpdate();

pstmt.close();
fis.close();

  同樣,我們也可以用類似的方法將Clob對象從資料庫中取出:

String sql = "select content from tbl_Articles where title = ?";
PreparedStatement pstmt = con.prepareStatement(sql) ;

pstmt.setString(1, "Iraq War");
ResultSet rs = pstmt.executeQuery() ;

rs.next() ;
Clob clob = rs.getClob("content") ;

InputStreamReader in = new InputStreamReader(clob.getAsciiStream()) ;

JTextArea text = new JTextArea(readString(in)) ;

rs.close();
pstmt.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.