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(); |