一般來說,我們使用框架進行關係型資料庫與物件型別的轉換時沒有過多注意。那麼在使用jdbc轉換物件時有一些物件可能會被忽略,例如CLOB欄位,下面是我在使用JDBC轉義CLOB時的處理。
public static List<Map<String,Object>> getDetail(final String instance,final String sql) throws Exception{
String key="";
Connection con=null;
Statement st=null;
ResultSet rs=null;
ResultSetMetaData rsmd=null;
List<Map<String,Object>> resultList =new ArrayList<Map<String,Object>>();
Map<String,String> jdbcMap=new HashMap<String,String>();
//取得jdbc連線串,此處省略掉,大家可以直接寫上jdbc配置
//jdbcMap=praseXml(instance);
try {
Class.forName(jdbcMap.get("driver"));
//這裡是由於配置的一個jdbc配置檔案加密了,需要解密 ,大家可以按自己的方式寫
con=DriverManager.getConnection(jdbcMap.get("url"),DesEncryptUtils.decrypt(jdbcMap.get("name")),DesEncryptUtils.decrypt(jdbcMap.get("pass")));
st = con.createStatement();
rs = st.executeQuery(sql);
rsmd=rs.getMetaData();
logger.info("...Running...");
int columnCount = rsmd.getColumnCount();
Map<String, Object> map = null;
while (rs.next()) {
map = new HashMap<String, Object>();
for (int i = 1; i <= columnCount; i++) {
key = rsmd.getColumnName(i);
//這裡就是我們主要的處理CLOB方法了。
if( rs.getObject(key) instanceof Clob){
Clob clob = rs.getClob(key);// java.sql.Clob型別
String clobValue=getClobString(clob);
map.put(key,clobValue);
}else{
Object value = rs.getObject(key);
map.put(key, value);
}
}
resultList.add(map);
}
}finally{
con.close();
st.close();
rs.close();
}
return resultList;
}
//處理CLOB主要方法
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 new String(sb.toString().getBytes("UTF-8"));
} catch (Exception e) {
return "";
}
}