Java基础之操作Oracle CLOB

//取CLOB中的内容(不包含图片)

  public String query(String strQuery) throws SQLException{

  if (con==null || con.isClosed()) {

  pool = ConnectionPool.getInstance();

  con = pool.getConnection();

  }

  Statement st = con.createStatement();

  ResultSet rs = st.executeQuery(strQuery);

  String line = "" ;

  String content = "";

  while (rs.next()){

  Clob clob = rs.getClob("content"); //和提取一般对象一样

  //   InputStream is = rs.getAsciiStream(1); //特殊的,对于与得到Clob的流

  //   BufferedReader br = new BufferedReader(new InputStreamReader(is));

  //

  //   while(null != (line = br.readLine())){

  //    //System.out.println(line);

  //    content += line;

  //   }

  //   is.close();

  long longLen = clob.length();

  content = clob.getSubString(1L, (int) longLen);

  }

  rs.close();

  st.close();

  con.close();

  return content;

  }

  //写入CLOB

  public Boolean update(DynaActionForm listForm) throws SQLException, IOException {

  // TODO 自动生成方法存根

  String content = (String) listForm.get("content");

  try {

  if (con==null || con.isClosed()) {

  pool = ConnectionPool.getInstance();

  con = pool.getConnection();

  }

  con.setAutoCommit(false);

  //插入一个空CLOB

  //String insertSql = "insert into  Client_PUBBLOB(id,content) values('1',empty_clob())";

  //查询插入的空CLOB

  String selectSql = "select content from  Client_PUBBLOB where id = '1' for update";

  //PreparedStatement  stmt = con.prepareStatement(insertSql);

  //stmt.executeUpdate();

  //stmt.close();

  //lock this line

  PreparedStatement pstmt = con.prepareStatement(selectSql);

  String emptyClobSql="update Client_PubBLOB set content=empty_clob() where id=1";

  PreparedStatement pstmt2=con.prepareStatement(emptyClobSql);

  pstmt2.executeUpdate();

  pstmt2.close();

  ResultSet rs = pstmt.executeQuery();

  if(rs.next()){

  oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob(1);

  //System.out.println("要修改的content:" + content);

  //为CLOB写信息

  String sql1="update Client_PubBLOB set content=? where id=1";

  clob.putChars(1, content.toCharArray());

  //    String s = clob.getSubString((long)1,(int)clob.length()-1);

  //    System.out.println("当前的clob内容是: " + s);

  pstmt=con.prepareStatement(sql1);

  pstmt.setClob(1,clob);

  pstmt.executeUpdate();

  //    oracle.sql.CLOB clob2 = (oracle.sql.CLOB)rs.getClob(1);

  //    String s = clob.getSubString((long)1,(int)clob.length()-1);

  //    System.out.println(s);

  }

  con.commit();

  pstmt.close();

  } catch (SQLException e) {

  con.rollback();

  } finally {

  con.setAutoCommit(true);

  con.close();

  }

  return listForm;

  }

  //不过貌似也可以直接写String进CLOB中,比如

  String data= dataInfo.getDetail();

  cs.setString(1, newsInfo.getSubject());

  cs.setString(2, newsInfo.getAuthor());

  cs.setString(3, newsdetail);



你可能感兴趣的:(java,oracle,sql)