JDBC 2.0 引入對 SQL3 標準新數據類型的支持:Blob(二進制大對象)、Clob(字符大對象)、Array、REF(對象引用)、UDT(用戶定義類型)。這些類型讓數據庫設計者能構建更豐富模式,大幅簡化複雜數據(圖片、文檔、多媒體)的持久化與處理。
String sql = "INSERT 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()); // 參數 2 對應 Blob 列
pstmt.executeUpdate();
pstmt.close();
fis.close();
String sql = "SELECT photo FROM tbl_User WHERE username = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
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);
// 將 photo 加入 Swing 界面即可顯示
rs.close();
pstmt.close();
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();
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();
| 類型 | 寫入方法 | 讀取方法 | 典型場景 |
|---|---|---|---|
| Blob | setBinaryStream / setBlob | getBlob / getBinaryStream / getBytes | 圖片、音視頻、序列化對象 |
| Clob | setAsciiStream / setCharacterStream / setClob | getClob / getAsciiStream / getCharacterStream / getSubString | 長文本、XML、JSON、日誌 |
getBinaryStream/getAsciiStream) 避免一次性載入巨大對象導致 OOMBlob.free()/Clob.free() (JDBC 4.0+) 及時釋放資源LONGBLOB/LONGTEXT 對應標準 Blob/Clob掌握 Blob/Clob 操作是處理企業級非結構化數據的基礎技能。JDBC 2.0 通過統一接口屏蔽了底層數據庫差異,配合流式處理,使 Java 應用能高效、安全地管理大對象數據,為富媒體應用奠定堅實數據層基礎。