java讀取blob,clob轉換為字串
阿新 • • 發佈:2018-11-17
直接上程式碼:
package com.it.test; import java.io.BufferedReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import oracle.sql.BLOB;public class Test { /*** * 讀取oracleCLOB欄位內容 * * @param conn * @return */ public static String readCLOB(Connection conn) { String sql = "select 大欄位1,大欄位2 from 印章基本資訊_char_ccbb where yzbm='2'"; String content = ""; try { conn.setAutoCommit(false); PreparedStatement ps1 = conn.prepareStatement(sql); ResultSet rs1 = ps1.executeQuery(); while (rs1.next()) { oracle.sql.CLOB clob = (oracle.sql.CLOB) rs1.getClob("大欄位1"); BufferedReader in = new BufferedReader(clob.getCharacterStream()); StringWriter out= new StringWriter(); int c; while ((c = in.read()) != -1) { out.write(c); } content = out.toString(); System.out.println(content);// 輸出CLOB內容 } } catch (Exception e) { e.printStackTrace(); } return content; } /*** * 讀取oracle的blob轉換為字串 * * @param conn * @return */ public static String ConvertBLOBtoString(Connection conn) { String newStr = ""; // 返回字串 long BlobLength; // BLOB欄位長度 byte[] bytes; // BLOB臨時儲存位元組陣列 int i = 1; // 迴圈變數 Statement st = null; try { st = conn.createStatement(); ResultSet rs = st.executeQuery("select 大欄位2 from 印章基本資訊_char_ccbb where yzbm='2'"); while (rs.next()) { BLOB blob = (BLOB) rs.getBlob("大欄位2"); byte[] msgContent = blob.getBytes(); // BLOB轉換為位元組陣列 BlobLength = blob.length(); // 獲取BLOB長度 if (msgContent == null || BlobLength == 0) // 如果為空,返回空值 { return ""; } else { while (i < BlobLength) // 迴圈處理字串轉換,每次1024;Oracle字串限制最大4k { bytes = blob.getBytes(i, 1024); i = i + 1024; newStr = newStr + new String(bytes, "gb2312"); } } } System.out.println(newStr); System.out.println(newStr.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return newStr; } }
以上內容參考自:https://blog.csdn.net/u010965170/article/details/78729794