首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JDBC 2.0 進階數據類型完全指南:Blob、Clob 與大對象處理實戰

     編輯:Java 相關知識

SQL3 新類型帶來的建模革命

JDBC 2.0 引入對 SQL3 標準新數據類型的支持:Blob(二進制大對象)、Clob(字符大對象)、Array、REF(對象引用)、UDT(用戶定義類型)。這些類型讓數據庫設計者能構建更豐富模式,大幅簡化複雜數據(圖片、文檔、多媒體)的持久化與處理。

Blob 實戰:圖片存儲與讀取

插入圖片到數據庫

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

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

關鍵 API 速查表

類型寫入方法讀取方法典型場景
BlobsetBinaryStream / setBlobgetBlob / getBinaryStream / getBytes圖片、音視頻、序列化對象
ClobsetAsciiStream / setCharacterStream / setClobgetClob / getAsciiStream / getCharacterStream / getSubString長文本、XML、JSON、日誌

最佳實踐提示

  • 大對象操作務必在事務中進行,確保原子性
  • 使用流式 API (getBinaryStream/getAsciiStream) 避免一次性載入巨大對象導致 OOM
  • Blob.free()/Clob.free() (JDBC 4.0+) 及時釋放資源
  • MySQL 中 LONGBLOB/LONGTEXT 對應標準 Blob/Clob

總結

掌握 Blob/Clob 操作是處理企業級非結構化數據的基礎技能。JDBC 2.0 通過統一接口屏蔽了底層數據庫差異,配合流式處理,使 Java 應用能高效、安全地管理大對象數據,為富媒體應用奠定堅實數據層基礎。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved