解析jdbc处理oracle的clob字段的详解
import java.io.bufferedoutputstream;
import java.io.bytearrayinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.io.reader;
import java.sql.clob;
import java.sql.connection;
import java.sql.resultset;
import java.sql.sqlexception;
public class clobutil {
/**
*
* @param insertsql 插入sql语句 有clob字段时,值必须设置成empty_clob()函数 例:insert into ba valus(1,empty_clob())
* @param updatesql 带有修改的查询语句,并应增加条件判断.例:select * from ba where ba_id = '"+ba.getba_id()+"' for update
* @param con 数据库链接
* @param bigstring 要插入的clob值
* @param updatecolumn 要插入的表字段名
* @return
* @throws sqlexception
*/
public static boolean clobinsert(string insertsql,string updatesql,connection con,string bigstring,string updatecolumn ) throws sqlexception{
// 结果集
resultset rs = null;
// 插入数据库的sql
string query = insertsql;
// 设置不自动提交
con.setautocommit(false);
// 定义预处理
java.sql.preparedstatement pstmt = con.preparestatement( query);
// 执行插入语句
pstmt.executeupdate();
//清空
pstmt = null;
// 执行更改
query = updatesql;
//显示执行带有修改方式的select
pstmt = con.preparestatement(query);
rs = pstmt.executequery();
// 采用流的方式处理结果集
if(rs.next())
{
// 得到指定的clob字段
oracle.sql.clob singnaturedateclob = (oracle.sql.clob)rs.getclob(updatecolumn);
// 把clob字段放到输出流当中
bufferedoutputstream out = new bufferedoutputstream(singnaturedateclob.getasciioutputstream());
// 判断传入的数据是否为空
if(bigstring!=null){
try{
// 把要保存的数据转换成输入流
inputstream is = (inputstream)(new bytearrayinputstream(bigstring.getbytes()));
copystream( is, out );
out.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
rs.close();
con.commit();
return true;
}
/**
* 将输入流写入到输出流当中
* @param is 输入流
* @param os 输出流
* @throws ioexception
*/
public static void copystream( inputstream is, outputstream os )
throws ioexception
{
byte[] data = new byte[4096];
int readed = is.read(data);
while (readed != -1)
{
os.write(data,0,readed);
readed = is.read(data);
}
}
/**
* 通过clob对象返回字符串
* @param c
* @return
*/
public static string getclobstring(clob c) {
try {
reader reader=c.getcharacterstream();
if (reader == null) {
return null;
}
stringbuffer sb = new stringbuffer();
char[] charbuf = new char[4096];
for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
sb.append(charbuf, 0, i);
}
return sb.tostring();
} catch (exception e) {
return "";
}
}
}
上一篇: Python使用字典的嵌套功能详解