메뉴 건너뛰기

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 537
420 Cannot create /var/run/oozie/oozie.pid: Directory nonexistent오류 2014.06.03 537
419 여러 홈페이지를 운영하거나 혹은 서버에 가입한 사용자들에게 홈페이지 계정을 나누어 줄수 있도록 설정/계정 생성방법 2018.01.23 536
418 halyard의 console스크립트에서 생성한 repository는 RDF4J Web Applications에서 공유가 되지 않는다. 2017.07.05 533
417 new Gson().toJson(new ObjectId())을 사용하면 값이 다르게 나오는 경우가 있음 2016.12.23 532
416 python실행시 ValueError: zero length field name in format오류 해결방법 2016.05.27 528
415 Could not configure server becase SASL configuration did not allow the Zookeeper server to authenticate itself properly: javax.security.auth.login.LoginException: Checksum failed 2019.05.18 525
414 hadoop 어플리케이션을 사용하는 사용자 변경시 바꿔줘야 하는 부분 2016.09.23 524
413 Error: E0501 : E0501: Could not perform authorization operation, User: hadoop is not allowed to impersonate hadoop 해결하는 방법 2015.06.07 521
412 AIX 7.1에서 hive실행시 "hive: line 86: readlink: command not found" 오류가 발생시 임시 조치사항 2016.09.25 520
411 Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging 발생시 조치사항 2017.04.19 519
410 [HIVESERVER2]프로세스의 thread및 stack trace를 덤프하는 방법(pstack, jstack) 2022.05.11 518
409 우분투 서버에 GUI로 접속하기 file 2018.05.27 518
408 fuseki에서 제공하는 script중 s-post를 사용하는 예문 2017.09.15 517
407 streaming작업시 입력된 값에 대한 사본을 만들게 되는데 이것이 실패했을때 발생하는 경고메세지 2017.04.03 517
406 서버중 slave,worker,regionserver만 재기동해야 할때 필요한 기동스크립트및 사용방법 2017.02.03 516
405 Soft memory limit exceeded (at 100.05% of capacity) 오류 조치 2022.01.17 515
404 우분투 16.04LTS에 Jupyter설치 2018.04.17 515
403 [Cloudera 6.3.4, Kudu]]Service Monitor에서 사용하는 metric중에 일부를 blacklist로 설정하여 모니터링 정보 수집 제외하는 방법 2022.07.08 514
402 Windows7 64bit 환경에서 Apache Hadoop 2.7.1설치하기 2017.07.26 513
위로