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 "";
}
}
}