您的位置:首页 > 数据库 > Oracle

JDBC插入Oracle的CLOB字段的简单实用的例子和几点注意事项

2009-12-21 20:39 483 查看
2009-12-21

//DBOperator是自写的库操作类
public static boolean setCLOB(String table, String column, String value, String whereSql){
DBOperator dbop = new DBOperator();
boolean defaultAutoCommint = false;
try{
dbop.setAutoCommit(false);
//#进行
ResultSet rs = dbop.query("select " + column + " from " + table + " " + whereSql + " for update" );
if(rs.next()){
oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob(column);
BufferedWriter writer = new BufferedWriter(clob.getCharacterOutputStream());
writer.write(value);
writer.flush();
writer.close();
dbop.commit();
rs.close();
}else{
rs.close();
Logger.logout("Faild insert CLOB because query sql string is not valid");
return false;
}

dbop.setDefaultAutoCommit();

dbop.close();
}catch(Exception ex){
Logger.logout("Found exception when insert values to CLOB columns ");
ex.printStackTrace();
try {
dbop.getConnector().rollback();
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return false;
}finally{
dbop.close();
}
return true;
}

注意事项:
第一
LOB数据不能象其它类型数据一样直接插入(INSERT)。插入前必须先插入一个空的LOB对象,CLOB类型的空对象 为EMPTY_CLOB (),BLOB类型的空对象为EMPTY_BLOB()。之后通过SELECT命令查询得到先前插入的记录并锁定, 继而将空对象修改为所要插入的LOB对象。
第二
在插入到更新之间一定要将自动提交设为false否则,再次查找时就不能正确更新,查找时一定要用select XXX from table where for update 如果不加for update会报:“row containing the LOB value is not locked”;如果在插入前没有将自动提交设为false会报 “fetch out of sequence ”。注意到以上两点一般就可以顺利插入clob型字段了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: