讀寫Oracle 10g的CLOB欄位

今天有個將超長字串寫入Oracle資料庫的需求,原先以為只要把欄位型態定義CLOB (Character Large OBject)再用setString填入即可,沒想到當字串長度超過8K時就會產生SQLException,哇,難道真的要用stream的方法來處理嗎?有點麻煩哩。還好,終於找到解決方法,但似乎只能用在Oracle10g上:

  1. Oracle 10g針對CLOB 形態做了加強,能直接用getStringsetString來讀寫CLOB欄位。
  • 字串長度最大32,765 Bytes
  • 必須使用Oracle 10gJDBC driver (ojdbc14.jar)
  • Varchar2最大只能設定到4000,因此有較長字串需處理時,可使用CLOB再限制長度為32765 (此長度應該對大部份應用都能適用)
  1. 存取超過32,765字串時的特殊處理:
    1. 使用擴充的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();
      
    2. 啟始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 );
      

##

您可能也會有興趣的類似文章

簡睿

服務於軟體業的資訊老兵。興趣廣泛,學習力佳,樂於分享所知所學。

您可能也會喜歡…

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *