메뉴 건너뛰기

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


번호 제목 날짜 조회 수
186 streaming작업시 입력된 값에 대한 사본을 만들게 되는데 이것이 실패했을때 발생하는 경고메세지 2017.04.03 1755
185 JavaStreamingContext를 이용하여 스트림으로 들어오는 문자열 카운트 소스 2017.03.30 1016
184 kafka-manager 1.3.3.4 설정및 실행하기 2017.03.20 3048
183 spark 2.0.0의 api를 이용하는 예제 프로그램 2017.03.15 1149
182 It is indirectly referenced from required .class files 오류 발생시 조치방법 2017.03.09 1828
181 spark2.0.0에서 hive 2.0.1 table을 읽어 출력하는 예제 소스(HiveContext, SparkSession, SQLContext) 2017.03.09 1148
180 spark에서 hive table을 읽어 출력하는 예제 소스 2017.03.09 1918
179 spark에서 hive table을 읽어 출력하는 예제 소스 2017.03.09 1765
178 서버중 slave,worker,regionserver만 재기동해야 할때 필요한 기동스크립트및 사용방법 2017.02.03 1834
177 테이블의 row수를 빠르게 카운트 하는 방법 2017.01.26 1033
176 HDFS상의 /tmp폴더에 Permission denied오류가 발생시 조치사항 2017.01.25 1282
175 [JSON 파싱]mongodb의 document를 GSON을 이용하여 parsing할때 ObjectId값에서 오류 발생시 조치방법 2017.01.18 1850
174 spark 2.0.0를 windows에서 실행시 로컬 파일을 읽을때 발생하는 오류 해결 방법 2017.01.12 1617
173 new Gson().toJson(new ObjectId())을 사용하면 값이 다르게 나오는 경우가 있음 2016.12.23 1803
172 like검색한 결과를 기준으로 집계를 수행하는 java 소스 2016.12.19 1804
171 MongoDB에 있는 특정컬럼의 값을 casting(string->integer)하여 update하기 java 소스 2016.12.19 1972
170 mongodb aggregation query를 Java code로 변환한 샘플 2016.12.15 2237
» ResultSet에서 데이타를 List<Map<String,String>>형태로 만들어서 리턴하는 소스(Collections.sort를 이용한 정렬 가능) 2016.12.15 2126
168 hbase startrow와 endrow를 지정하여 검색하기 샘플 2016.12.07 1004
167 Mountable HDFS on CentOS 6.x(hadoop 2.7.2의 nfs기능을 이용) 2016.11.24 1880
위로