매번 ibatis처럼 쿼리를 xml에 정의해놓고 사용했었는데,

이번엔 프로젝트 특성상 view단에서 Select쿼리를 직접 날려야하는 상황이 발생했다..

막상 구현하려니 막막함.. 우허어엉.. 


결국, 고민끝에 원시적인 JDBC방법을 택함.. (역시 난 단순함..)


기본적인 사용법은 다른 블로그에도 나와있을테니, 조금 별난 부분만 내 블로그에서 다루려한디..


1 . ResultSetMetaData를 이용한 컬럼명,컬럼타입 알아내기.

 : 어떤 Select 쿼리가 실행되서 어떤 결과가 나올지 모르므로, 결과를 유연하게 처리해야하는게 큰 이슈였음.

 : 그래서 ResultSetMetadata로 컬럼결과에 대한 컬럼명,컬럼타입을 저장하고,

 : 이 후에 이를 활용해 ResultSet에서 값을 가져옴.

rs = stmt.executeQuery(query);
			
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List columnInfoList = new ArrayList();
for(int i=1;i<=columnCount;i++){
   Map infoMap = new HashMap();
   String columnName = rsmd.getColumnName(i);
   int columType = rsmd.getColumnType(i);
				
   infoMap.put("columName", columnName);
   infoMap.put("columType", columType);
   columnInfoList.add(infoMap);
}

//중략...
while(rs.next()){
   Map resultMap = new HashMap();
   for(int i=0;i<=columnCount-1;i++){
        Map columnInfoMap = (Map) columnInfoList.get(i);
        int columnType = (Integer) columnInfoMap.get("columType");
        String columnName = (String) columnInfoMap.get("columName");
        Object result = getResultValue(columnType,columnName,rs, query);
        resultMap.put(columnName,result);
        //logger.debug("[QueryDAO] "+columnName+" : "+result);
    }
    resultList.add(resultMap);
}
public Object getResultValue(int columnType,String columnName, ResultSet rs, String query) throws SQLException{
		if(columnType == Types.NUMERIC || columnType == Types.BIGINT || columnType == Types.INTEGER || columnType == Types.BIT){
			return rs.getInt(columnName);
		}else if(columnType == Types.CHAR || columnType == Types.VARCHAR){
			String result = rs.getString(columnName); 
			if(result == null)
				return "";
			return result;
		}else if(columnType == Types.CLOB){
			StringBuilder sb = new StringBuilder();
			Clob clob = rs.getClob(columnName);
			if(clob==null){
				logger.debug("[ QueryDAO Clob is Null ] ");
				logger.debug("	query : "+query);
				logger.debug("	Null Column : "+columnName);
				return "";
			}
			Reader reader = clob.getCharacterStream();
			char[] buff = new char[1024];
			int nchar = 0;
			try {
				while((nchar = reader.read(buff))!= -1){
					sb.append(buff,0,nchar);
				}
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage());
			} finally{
				if(reader!=null){
					try {
						reader.close();
					} catch (IOException e) {
						throw new RuntimeException(e.getMessage());
					}
				}//end if
			}
			return sb.toString();
		}else if(columnType == Types.BLOB){
			StringBuilder sb = new StringBuilder();
			InputStream is = rs.getBlob(columnName).getBinaryStream();
			byte[] buff = new byte[1024];
			int nchar = 0;
			try {
				while((nchar = is.read(buff))!= -1){
					sb.append(new String(buff,0,nchar));
				}
			} catch (IOException e) {
				throw new RuntimeException(e.getMessage());
			} finally{
				if(is!=null)
					try {
						is.close();
					} catch (IOException e) {
						throw new RuntimeException(e.getMessage());
					}
			}
			return sb.toString();
		}else if(columnType == Types.DATE || columnType == Types.TIMESTAMP || columnType == Types.TIME){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(rs.getDate(columnName));
		}else{
			logger.debug("[ QueryDAO Unsupported Column Type ] ");
			logger.debug("	query : "+query);
			logger.debug("	unsupported Column : "+columnName);
			logger.debug("	unsupported Column Type : "+columnType);
			return "";
		}
	}





2. 총 Row갯수 구하기.

  : ResultSet에서는 안타깝게도, size, length 이딴게 업다아아아!!!! 

  : 하지만 방법이 있디..


먼저 Statement를 만들때, 옵션을 주고, ResultSet의 결과를 받을때, 마지막으로 가서 Row Index를 얻은 후 다시 맨처음으로 돌아가는 방식이다.
stmt = c.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
//중략..
rs.last(); 
rowCount = rs.getRow();
rs.beforeFirst();


다른 카테고리의 글 목록

Workspace/Web Dev 카테고리의 포스트를 톺아봅니다