2007年06月30日
讀寫Oracle 10g的CLOB欄位
今天有個將超長字串寫入Oracle資料庫的需求,原先以為只要把欄位型態定義CLOB (Character Large OBject) 再用setString填入即可,沒想到當字串長度超過8K時 就會產生SQLException,哇,難道真的要用stream的方法來處理嗎?有點麻煩哩。還好,終於找到解決方法,但似乎只能用在Oracle 10g上:
- Oracle 10g針對CLOB 形態做了加強,能直接用getString和setString來讀寫CLOB欄位。
- 字串長度最大32,765 Bytes
- 必須使用Oracle 10g的JDBC driver (ojdbc14.jar)
- Varchar2最大只能設定到4000,因此有較長字串需處理時,可 使用CLOB再限制長 度為32765 (此 長度應該對大部份應用都能適用)
- 要存 取超過32,765字串時的特殊處理:
- 使 用擴充的setStringForClob method:
opstmt = (OraclePreparedStatement)conn.prepareStatement(sql);
// Use the new method to insert the CLOB data (for data greater or lesser than 32 KB)
opstmt.setStringForClob(1,str);
// Execute the OraclePreparedStatement
opstmt.executeUpdate(); - 啟始Driver時設定參數
// Load the database details into the variables.
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "scott";
String password = "tiger";
// Create the properties object that holds all database details
Properties props = new Properties();
props.put("user", user );
props.put("password", password);
props.put("SetBigStringTryClob", "true");
// Load the Oracle JDBC driver class.
DriverManager.registerDriver(new OracleDriver());
// Get the database connection
Connection conn = DriverManager.getConnection( this.url, this.props );
- 使 用擴充的setStringForClob method:
引用URL
http://cgi.blog.roodo.com/trackback/3554815
