在oracle里插入CLOB的程序

来源:互联网 发布:mysql 触发器 死锁 编辑:程序博客网 时间:2024/05/21 11:21

import JAVA.io.*;
import JAVA.sql.*;

import com.weasel.jdbc.core.db.DBManager;

public class CBLob {
 /*
  * 一个插入CLOG的程序
  * docxml在数据库里是一个大字段,
  * */
 DBManager mgr=new DBManager();

 public int insertDocument(int docid, String context) {
  int flag = 0;
  String sql = "insert into  document(docid,docxml)"
    + " values(?,EMPTY_CLOB())";
  String sqlclob = "SELECT docxml FROM document WHERE docid=? FOR UPDATE";
  Connection conn=null;
  PreparedStatement pstmt = null;
  Statement stmt = null;
  ResultSet rs = null;
  try {
   conn=mgr.getConnection();
   conn.setAutoCommit(false);//必须取消自动提交,否则下面无法执行。
   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, docid);   
   pstmt.executeUpdate();
   pstmt.close();
   //System.out.println("insert into document:" + docid);
   //取大字段
   pstmt=conn.prepareStatement(sqlclob);
   pstmt.setInt(1, docid);
   rs=pstmt.executeQuery();
   while (rs.next()) {
    oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob("docxml");
    BufferedWriter out = new BufferedWriter(clob
      .getCharacterOutputStream());
    StringReader in = new StringReader(context);
    int c;
    while ((c = in.read()) != -1) {
     out.write(c);
    }
    in.close();
    out.close();
   }
   rs.close();
   stmt.close();
   conn.commit();
   conn.setAutoCommit(true);//恢复自动提交,否则别的数据无法提交。
   flag = 1;
  } catch (SQLException e) {
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   mgr.disConnect();
  }  
  return flag;
 }}