针对oracle数据库,在我们后台需要入库clob字段类型时,sql应该怎么写呢?
最近遇到这个问题,于是了解了下并作记录(以表test为例,含有id-number,name-vachar2,content-clob三个类型字段):
1、当确认clob字段的数据长度不超过oracle中字符串最大长度限制,则可以直接使用单引号和字符串一样入库,即
insert into test (id,name,content)values(1,'name1','xxxxx');
2、一般情况下,clob用于存储大段文字或其他字符数据,其长度是超过oracle字符串最大长度限制的,此时不能再简单用单引号入库,应该使用oracle内置方法to_clob()。先将需要存入的数据转化一下结构:
public class GetClobStr {
/**
* @Author Administrator
* @Description 将字符串根据特定长度分割成字符串数组并拼接成正确格式
* 格式 to_clob('xx')||to_clob('xx')||...
* @Param @param s
* @Param @param len 每个clob串的字符长度
* @Param @return(参数)
* @Return String
*/
public static String stringSpilt(String s,int len){
StringBuffer sb=new StringBuffer();
int spiltNum=(s.length())/len;
if(spiltNum==0){
sb.append("to_clob('"+s+"')");
}else {
for(int i=0;i<s.length();i+=len){
if((i+len)>=s.length()){
sb.append("to_clob('"+s.substring(i, s.length())+"')");
}else{
sb.append("to_clob('"+s.substring(i, i+len)+"')||");
}
}
}
return sb.toString();
}
}
此时sql可以这样写:
StringBuffer sb=new StringBuffer().append("insert into test(id,name,content) values (2,'name2',")
.append(GetClobStr.stringSpilt(源字符串,len))
.append(");");
(len根据自己需求分配每个to_clob()串的字符长度)