top
Loading...
JDBC2.0中的高級數據類型

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

(T111)

本文選自飛思圖書《精通Java核心技術》

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗