메뉴 건너뛰기

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;
	         }
		}
	}


번호 제목 날짜 조회 수
430 impala2를 Cloudera Manager가 아닌 수동으로 설치하는 방법 2018.05.30 4162
429 hive metastore db중 TBLS, TABLE_PARAMS테이블 설명 2021.10.22 4160
428 java.lang.OutOfMemoryError: unable to create new native thread오류 발생지 조치사항 2016.10.17 4160
427 ubuntu에 maven 3.6.1설치 및 환경변수 설정 2019.06.02 4156
426 Ubuntu 16.04 LTS에 4대에 Hadoop 2.8.0설치 2017.05.01 4155
425 AIX 7.1에 Python 2.7.11설치하기 2016.10.06 4155
424 kerberos설정된 상태의 spooldir->memory->hdfs로 저장하는 과정의 flume agent configuration구성 예시 2019.05.30 4147
423 spark 2.3.0을 설치하가 위해서 parcel에 다음 url을 입력한다. 2018.07.15 4146
422 자주쓰는 유용한 프로그램 2018.03.16 4146
421 "File /user/hadoop/share/lib does not exist" 오류 해결방법 2015.06.07 4146
420 [Impala TLS/SSL이슈]RangerAdminRESTClient.java:151] Failed to get response, Error is: TrustManager is not specified 2023.02.02 4144
419 It is indirectly referenced from required .class files 오류 발생시 조치방법 2017.03.09 4144
418 oozie 4.1 설치 - maven을 이용한 source compile on hadoop 2.5.2 with postgresql 9.3 2015.04.30 4144
417 cloudera에서 spark-shell를 실행했을때 default master는 spark.master=yarn-client임 2018.06.20 4137
416 DB별 JDBC 드라이버 2015.10.02 4136
415 Failed to write to server: (no server available): 2022.01.17 4135
414 [Sentry]HDFS의 ACL을 Sentry와 연동후 테스트 2020.06.02 4130
413 source, sink를 직접 구현하여 사용하는 예시 2019.05.30 4128
412 [kudu]테이블 drop이 안되고 timeout이 걸리는 경우 조치 방법 2020.06.08 4123
411 HUE를 사용할 사용자를 추가 하는 절차 2018.05.29 4112
위로