首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

Java 操作 Oracle CLOB 欄位完整指南:寫入、查詢與驗證

     編輯:Oracle 資料庫相關知識

CLOB (Character Large Object) 適用於儲存大型文本(如 XML、文件內容),最大 4GB。本文示範 JDBC 操作 CLOB 的標準流程:插入 EMPTY_CLOB()、取得定位器、寫入字元流、查詢讀取、SQL*Plus 驗證。

環境假設

  • 資料表:clobtest_table (id VARCHAR2, picstr CLOB)
  • 已建立 Connection conn,且 String strTmp 含待寫入大文本

一、插入 CLOB 資料

conn.setAutoCommit(false);
String sql = "INSERT INTO clobtest_table(id, picstr) VALUES (?, EMPTY_CLOB())";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "001");
pstmt.executeUpdate();
pstmt.close();

// 取得 CLOB 定位器
sql = "SELECT picstr FROM clobtest_table WHERE id = '001' FOR UPDATE";
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
oracle.sql.CLOB clob = null;
if (rs.next()) clob = (oracle.sql.CLOB) rs.getClob(1);
rs.close(); pstmt.close();

// 寫入字元資料
Writer writer = clob.getCharacterOutputStream();
writer.write(strTmp);
writer.flush();
writer.close();

conn.commit();

二、SQL*Plus 驗證長度

SQL> SELECT DBMS_LOB.GETLENGTH(picstr) FROM clobtest_table;

三、查詢讀取 CLOB

String sql = "SELECT picstr FROM clobtest_table WHERE id = '001'";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
String description = "";
if (rs.next()) {
  oracle.sql.CLOB clob = (oracle.sql.CLOB) 
    ((oracle.jdbc.driver.OracleResultSet) rs).getClob(1);
  if (clob == null || clob.length() == 0) {
    description = "";
  } else {
    description = clob.getSubString(1L, (int) clob.length());
    System.out.println("內容: " + description);
  }
}
rs.close(); pstmt.close();

關鍵注意事項

  • 寫入前必須 FOR UPDATE 鎖定列,否則定位器無效。
  • 使用 oracle.sql.CLOB 而非標準 java.sql.Clob 以存取 getCharacterOutputStream()、getSubString() 等 Oracle 擴充方法。
  • 大量文本建議分塊讀寫,避免記憶體壓力。
  • 交易未提交前,其他會話不可見。

掌握 CLOB 標準操作模式,能安全高效處理大型文本資料。

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