다연이네

[days05] ResultSet 결과물에 대한 정보 추출, 사용 예제, ResultSetMetaData 본문

JDBC

[days05] ResultSet 결과물에 대한 정보 추출, 사용 예제, ResultSetMetaData

 다연  2020. 11. 29. 20:50
반응형
package days05;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Scanner;

import com.util.DBConn;

/**
 * @author dayeon
 * @date 2020. 11. 27-오후 3:48:37
 * @subject ResultSet 결과물에 대한 정보 추출, 사용 예제
 * @content
 */

public class Ex03 {

	public static void main(String[] args) {
		//select * from emp; 쿼리 날렸을때 결과물을 rs가 담고 있는 것
		String sql = "SELECT table_name " + 
				" FROM tabs " + 
				" order by table_name ASC";

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

		con = DBConn.getConnection();

		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();

			int no = 1;
			while (rs.next()) {
				System.out.printf("%d. %s\n",no++, rs.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				pstmt.close();
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}//finally

		//
		System.out.print("> 테이블을 선택하세요?");
		Scanner scanner = new Scanner(System.in);
		String tableName = scanner.next();//테이블 이름 저장하기

		sql = "SELECT * FROM "+ tableName; //컬럼명이나 테이블명은 ? 못씀ㅠㅠ
		try {
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			//rs 객체로부터 정보 (컬럼개수, 컬럼명, 컬럼자료형 등등) 추출
			ResultSetMetaData rsmd=  rs.getMetaData(); //rs의 정보를 얻어오는 메소드
			//리턴값은 마우스 대서 복붙
			//컬럼개수 출력
			System.out.println("> 컬럼 개수 : "+rsmd.getColumnCount());

			System.out.println("--------------------------------------------------------------------------------------------");
			for (int i =1; i <= rsmd.getColumnCount(); i++) {
				System.out.printf("%s\t", rsmd.getColumnName(i));
			}
			System.out.println();
			System.out.println("--------------------------------------------------------------------------------------------");
			//나중에는 칼럼 개수만큼 선 길이도 늘리게 코딩
			//rs.next();
			 while(rs.next()) {
			//rs.getInt("empno"); //어떤 테이블을 선택하냐에 따라 다르니까 get int/double/String 정할수가 없어 
			for (int i = 1; i <=rsmd.getColumnCount(); i++) {
				//크게는 String, int, Date, double (자주쓰는애들)
				//System.out.println(rsmd.getColumnType(i)); //1, 12 등 숫자형을 돌림
				//System.out.println(rsmd.getColumnTypeName(i)); //NUMBER, VARCHAR2 등 문자 돌림
				int scale = rsmd.getScale(i); // Number(7,2) 뒤에 2가 scale임
				int columnType = rsmd.getColumnType(i);

				if (columnType == Types.NUMERIC && scale ==0) { //정수란 소리
					System.out.printf("%d\t",rs.getInt(i));

				}else if(columnType == Types.NUMERIC && scale !=0) {//실수란 소리
					System.out.printf("%.2f\t", rs.getDouble(i));

				}else if(columnType == Types.VARCHAR|| columnType == Types.CLOB) {//문자
					System.out.printf("%s\t", rs.getString(i));

				}else if(columnType == Types.DATE|| columnType == Types.TIMESTAMP) {//날짜
					System.out.printf("%tF\t",  rs.getDate(i));
					//날짜는 %f , %tF, %s 상관 없음

				}//if
			
				}//for
			System.out.println();
			}//while
			System.out.println();
			System.out.println("--------------------------------------------------------------------------------------------");

		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}


	}//main

}//class

반응형
Comments