【數據庫】java存取oracle大數據clob類型

數據庫表結構
DecryptDataIntf: java實體類,對應於數據庫表字段

1.java存入Oracle大數據clob類型

public void addData(DecryptDataIntf decryptData) throws SQLException, IOException{
		Writer outStream = null;
		//1.插入語句中添加empty_clob()
		String insertSQL="insert into Decrypt_data_intf (Trans_Id,Request_Content,Invoke_Resule) values(?,empty_clob(),?)";
		if(insertPstm==null)
			insertPstm=conn.prepareStatement(insertSQL);
		insertPstm.setString(1,decryptData.getTransId());
		insertPstm.setLong(2, decryptData.getInvokeResule());
		insertPstm.executeUpdate();
		String queryToUpdateSql="select Request_Content from Decrypt_data_intf where Trans_Id=? for update";
		if (updatePstm==null) 
			updatePstm=conn.prepareStatement(queryToUpdateSql);
		updatePstm.setString(1, decryptData.getTransId());
		//必加語句,重要
		conn.setAutoCommit(false);
		ResultSet rs = updatePstm.executeQuery();
		if (rs.next()){
			  //得到java.sql.Clob對象後強制轉換爲oracle.sql.CLOB
			  oracle.sql.CLOB clob = (oracle.sql.CLOB) rs.getClob("Request_Content");
			  outStream = clob.getCharacterOutputStream();
			  //decryptData.getRequestContent()是傳入的字符串
			  char[] c = decryptData.getRequestContent().toCharArray();
			  outStream.write(c, 0, c.length);
		  }
		rs.close();
		outStream.flush();
		conn.commit();	
		outStream.close();

	}

2.clob類型轉字符串

public String ClobToString(Clob clob) throws SQLException, IOException {

		String reString = "";
		Reader is = clob.getCharacterStream();// 得到流
		BufferedReader br = new BufferedReader(is);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {// 執行循環將字符串全部取出付值給StringBuffer由StringBuffer轉成STRING
			sb.append(s);
			s = br.readLine();
		}
		reString = sb.toString();
		is.close();
		br.close();
		return reString;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章