java.sql.Clob 對應 CLOB,提供兩種讀取流:
getCharacterStream():Unicode 字元流 (Reader),中文必用getAsciiStream():ASCII 位元組流 (InputStream)
Connection conn = ...;
conn.setAutoCommit(false); // 關鍵:避免「違反讀取順序」錯誤
// 1. 分配 Locator
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO test(id, content) VALUES (?, EMPTY_CLOB())");
ps.setInt(1, 1);
ps.executeUpdate();
// 2. 取回 Locator 並寫入內容
ResultSet rs = conn.createStatement().executeQuery(
"SELECT content FROM test WHERE id=1 FOR UPDATE");
rs.next();
Clob clob = rs.getClob(1);
Writer writer = clob.setCharacterStream(1);
writer.write("中文測試內容...");
writer.close();
// 3. 提交
conn.commit();
conn.setAutoCommit(true);
public class ECov {
// JSP/Servlet ISO-8859-1 → 資料庫 GB2312
public static String gb2asc(String gb) {
if (gb == null) return null;
try { return new String(gb.getBytes("GB2312"), "ISO8859_1"); }
catch (Exception e) { return gb; }
}
// 資料庫 ISO-8859-1 → 頁面 GB2312
public static String asc2gb(String asc) {
if (asc == null) return null;
try { return new String(asc.getBytes("ISO8859_1"), "GB2312"); }
catch (Exception e) { return asc; }
}
}
用法:寫入前 ECov.gb2asc(str),讀出後 ECov.asc2gb(str)。Oracle 預設以 ISO-8859-1 儲存。
java:comp/env/jdbc/OracleDS)DriverManager.getConnectionsetDate/getDate 非想像中簡單,時區、格式易出錯。建議統一用 TIMESTAMP WITH TIME ZONE 或應用層處理格式化。