public class ClobUtil {
/**
*
* @param insertSQL 插入sql語(yǔ)句 有clob字段時(shí),值必須設(shè)置成empty_clob()函數(shù) 例:insert into ba valus(1,empty_clob())
* @param updateSQL 帶有修改的查詢(xún)語(yǔ)句,并應(yīng)增加條件判斷.例:select * from BA where ba_id = '"+ba.getBA_id()+"' for update
* @param con 數(shù)據(jù)庫(kù)鏈接
* @param bigString 要插入的clob值
* @param updateColumn 要插入的表字段名
* @return
* @throws SQLException
*/
public static Boolean clobInsert(String insertSQL,String updateSQL,Connection con,String bigString,String updateColumn ) throws SQLException{
// 結(jié)果集
ResultSet rs = null;
// 插入數(shù)據(jù)庫(kù)的sql
String query = insertSQL;
// 設(shè)置不自動(dòng)提交
con.setAutoCommit(false);
// 定義預(yù)處理
java.sql.PreparedStatement pstmt = con.prepareStatement( query);
// 執(zhí)行插入語(yǔ)句
pstmt.executeUpdate();
//清空
pstmt = null;
// 執(zhí)行更改
query = updateSQL;
//顯示執(zhí)行帶有修改方式的select
pstmt = con.prepareStatement(query);
rs = pstmt.executeQuery();
// 采用流的方式處理結(jié)果集
if(rs.next())
{
// 得到指定的clob字段
oracle.sql.CLOB singnaturedateClob = (oracle.sql.CLOB)rs.getClob(updateColumn);
// 把clob字段放到輸出流當(dāng)中
BufferedOutputStream out = new BufferedOutputStream(singnaturedateClob.getAsciiOutputStream());
// 判斷傳入的數(shù)據(jù)是否為空
if(bigString!=null){
try{
// 把要保存的數(shù)據(jù)轉(zhuǎn)換成輸入流
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;
}
/**
* 將輸入流寫(xiě)入到輸出流當(dāng)中
* @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);
}
}
/**
* 通過(guò)Clob對(duì)象返回字符串
* @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 "";
}
}
}