1. 程式人生 > >Java更新Oracle的CLOB欄位的值

Java更新Oracle的CLOB欄位的值

Java用JDBC操作Oracle的CLOB欄位也是算最近遇到的一個知識點,也算是基礎,在此記錄一篇。

因為CLOB型別的特殊性,並不能通過for update進行操作,那麼就需要java將要修改的值通過流寫入到clob中。

那麼更新CLOB之前需要先清空CLOB的值

update xxxx.data_interface_config set SQL_ORDER=empty_clob() where id='79b15cbc011048569e6e64b5bf033dbf'

插入新的CLOB值

Writer outStream = null;
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
String modifySQL = "CLOB Value";
String updateSQL = "select * from mm_console.data_interface_config where id='79b15cbc011048569e6e64b5bf033dbf' for UPDATE ";
try {
    conn = getConnection();
    conn.setAutoCommit(autocommit); //關閉自動提交
    statement = conn.createStatement();
    resultSet = statement.executeQuery(updateSQL);
    if (resultSet.next()) {
         oracle.sql.CLOB clob = (oracle.sql.CLOB) resultSet.getClob(columnName);
         outStream = clob.getCharacterOutputStream();
         char[] c = modifySQL.toCharArray();
         outStream.write(c, 0, c.length);
     }
     outStream.flush();
     conn.commit();
     System.out.println("commit success!!!");
} catch (Exception e) {
     e.printStackTrace();
} finally {
    if (outStream != null) {
         try {
             outStream.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
    }
    closeConnStmtRs(conn, statement, resultSet);
}

如此,就可以對已存在的CLOB欄位進行更新操作了。