메뉴 건너뛰기

Cloudera, BigData, Semantic IoT, Hadoop, NoSQL

Cloudera CDH/CDP 및 Hadoop EcoSystem, Semantic IoT등의 개발/운영 기술을 정리합니다. gooper@gooper.com로 문의 주세요.


Mariadb에 접근하여 쿼리를 수행하고 필요시 정렬하여 List<Map<String, String>>에 담아서 리턴하는 메세드 예제


private final List<Map<String, String>> getResult (String query, String[] idxVals) throws Exception {
		String db_server = ;
		String db_port = ;
		String db_name = ;
		String db_user = ;
		String db_pass = ;

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		
		try {
			Class.forName("org.mariadb.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mariadb://" + db_server + ":" + db_port + "/" + db_name, db_user,  db_pass);
			
			pstmt = conn.prepareStatement(query);
			rs = pstmt.executeQuery();

			int cnt = 0;
	
			ResultSetMetaData md = rs.getMetaData();
			int columns = md.getColumnCount();
			while (rs.next()){
			   HashMap<String,String> row = new HashMap<String, String>(columns);
			   for(int i=1; i<=columns; i++){           
				   row.put(md.getColumnName(i), rs.getObject(i).toString());
			   }
			   //log.debug("row("+(cnt++)+")  ===========>"+row.toString());
			    list.add(row);
			}
			
			// 정렬(test)
	        // Collections.sort(list, new MapStringComparator("rest_type"));
	        //Collections.sort(list, new MapStringComparator("corner_id"));
	        //Collections.sort(list, new MapFloatComparator("cnt"));
	        
			return list;
		} catch (Exception e) {
			throw e;
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException sqle) {
				}
			if (pstmt != null)
				try {
					pstmt.close();
				} catch (SQLException sqle) {
				}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException sqle) {
				}
			}
		}
	}


*정렬을 위해서 사용되는 클래스(문자열)

class MapStringComparator implements Comparator<Map<String, String>> {
		private final String key;
		
		public MapStringComparator(String key) {
			this.key = key;
		}
		
		@Override
		public int compare(Map<String, String> first, Map<String, String> second) {
			String firstValue =first.get(key);
	        String secondValue = second.get(key);
	        
	         // 내림차순 정렬
             return firstValue.compareTo(secondValue);
		}
	}


*정렬을 위해서 사용되는 클래스(숫자)

class MapFloatComparator implements Comparator<Map<String, String>> {
		private final String key;
		
		public MapFloatComparator(String key) {
			this.key = key;
		}
		
		@Override
		public int compare(Map<String, String> first, Map<String, String> second) {
			float firstValue = Float.valueOf(first.get(key));
	         float secondValue = Float.valueOf(second.get(key));
	         
			// 내림차순 정렬
	         if (firstValue > secondValue) {
	             return -1;
	         } else if (firstValue < secondValue) {
	             return 1;
	         } else /* if (firstValue == secondValue) */ {
	             return 0;
	         }
		}
	}


번호 제목 날짜 조회 수
421 github에 있는 프로젝트와 로컬에서 작업한 프로젝트 합치기 2016.11.22 527
420 원격의 origin/master를 기준으로 dev branch를 만들어 작업후 원격의 origin/dev에 push하는 방법 file 2016.11.22 534
419 Mountable HDFS on CentOS 6.x(hadoop 2.7.2의 nfs기능을 이용) 2016.11.24 451
418 S2RDF를 이용한 다른 버젼의 github링크 2016.12.02 274
417 Jena 2.3를 Hadoop 2.7.2의 NFS로 mount하고 fuseki를 이용하여 start할때 오류 메세지 2016.12.02 1644
416 jena의 data폴더를 hadoop nfs를 이용하여 HDFS상의 폴더에 마운트 시키고 fuseki를 통하여 inert를 시도했을때 transaction 오류 발생 2016.12.02 174
415 hbase startrow와 endrow를 지정하여 검색하기 샘플 2016.12.07 185
» ResultSet에서 데이타를 List<Map<String,String>>형태로 만들어서 리턴하는 소스(Collections.sort를 이용한 정렬 가능) 2016.12.15 381
413 Collections.sort를 이용한 List<User>형태의 데이타 정렬(숫자, 문자에 대해서 각각 asc/desc및 복합정렬) 2016.12.15 395
412 Collections.sort를 이용한 List<Map<String, String>>형태의 데이타 정렬 소스 2016.12.15 360
411 mongodb aggregation query를 Java code로 변환한 샘플 2016.12.15 953
410 MongoDB에 있는 특정컬럼의 값을 casting(string->integer)하여 update하기 java 소스 2016.12.19 341
409 like검색한 결과를 기준으로 집계를 수행하는 java 소스 2016.12.19 492
408 Class.forName을 이용한 메서드 호출 샘플소스 2016.12.21 465
407 new Gson().toJson(new ObjectId())을 사용하면 값이 다르게 나오는 경우가 있음 2016.12.23 512
406 List<Map<String, String>>형태의 데이타에서 중복제거 하는 방법 2016.12.23 2046
405 Halyard - RDF4J와 Apache HBase를 이용하여 구현된 TripleStore이며 SPARQL 1.1쿼리를 지원한다. 2016.12.29 734
404 eclipse 3.1 단축키 정리파일 2017.01.02 117
403 [MemoryLeak분석]다수의 MongoCleaner 쓰레드가 Sleep상태에 있으면서 Full GC가 계속 발생되는 문제 해결방법 file 2017.01.11 355
402 spark 2.0.0를 windows에서 실행시 로컬 파일을 읽을때 발생하는 오류 해결 방법 2017.01.12 311
위로