Backend/JAVA_JDBC

05. JDBC, 테이블에서 행 가져오기 (select)

개발개발빈이 2022. 6. 17. 19:30

○ JDBC  테이블에서 한 개 행 가져오기

    - ResultSet : select문을 실행한 결과(논리적 테이블)을 저장 → 인터페이스

    - executeQuery() → select문 실행

 

        ① SQL작성 : 모든 칼럼을 가져온다고 해도 select * 사용자제

StringBuilder sql=new StringBuilder();
sql.append(" SELECT sno, uname, kor, eng, mat, tot, aver, addr, wdate ");
sql.append(" FROM sungjuk ");
sql.append(" WHERE sno=? ");

 

        ② SQL형식으로 변환 및 변수 대입 : sno=22인행 가져오기

pstmt = con.prepareStatement(sql.toString());
pstmt.setInt(1, 22);

 

        ③ SQL문 실행 : rs에 실행결과를 저장

ResultSet rs = null;
rs = pstmt.executeQuery();

 

        ④ 가져온 행에 접근

            - rs에 담기면 cursor가 담겨있는 자료의 젤 위에 줄을 가리킴

            - rs.next() : 가리킬 대상이 있으면 true, 없으면 false 반환

            - 자료형을 일치시키면서 가져와야 함

if(rs.next()){
    System.out.println("자료있음");

    // 1) 칼럼순서 접근 (칼럼의 순서 = 쿼리문에 쓴 순서)
    System.out.println(rs.getInt(1));    //1번 칼럼, sno칼럼
    System.out.println(rs.getString(2)); //2번 칼럼, uname칼럼
    System.out.println(rs.getInt(3));    //3번 칼럼, kor칼럼
    System.out.println(rs.getInt(4));    //4번 칼럼, eng칼럼
    System.out.println(rs.getInt(5));    //5번 칼럼, mat칼럼
    System.out.println(rs.getInt(6));    //6번 칼럼, tot칼럼
    System.out.println(rs.getInt(7));    //7번 칼럼, aver칼럼
    System.out.println(rs.getString(8)); //8번 칼럼, addr칼럼
    System.out.println(rs.getString(9)); //9번 칼럼, wdate칼럼
				
    // 2) 칼럼명으로 접근(칼럼명은 따옴표 안에)
    System.out.println(rs.getInt("sno"));
    System.out.println(rs.getString("uname"));
    System.out.println(rs.getInt("kor"));
    System.out.println(rs.getInt("eng"));
    System.out.println(rs.getInt("mat"));
    System.out.println(rs.getInt("tot"));
    System.out.println(rs.getInt("aver"));
    System.out.println(rs.getString("addr"));
    System.out.println(rs.getString("wdate"));
				
    }else {
        System.out.println("자료없음");
    }

 

○ JDBC  테이블에서 여러 행 가져오기

     - 한 행 가져오기와 비슷한데 rs를 전부가져올 때 까지 do~while 반복문 사용

pstmt = con.prepareStatement(sql.toString());
rs = pstmt.executeQuery();
if(rs.next()) {//cursor가 있는지?
    System.out.println("자료있음");
    do {
        System.out.print(rs.getInt("sno") + " ");
        System.out.print(rs.getString("uname") + " ");
        System.out.print(rs.getInt("kor") + " ");
        System.out.print(rs.getInt("eng") + " ");
        System.out.print(rs.getInt("mat") + " ");
        System.out.print(rs.getInt("aver") + " ");
        System.out.print(rs.getString("addr") + " ");
        System.out.print(rs.getString("wdate") + " ");
        System.out.println();
    }while(rs.next());	//다음 cursor가 있는지
}else {
    System.out.println("자료없음");
}

 

    - 전체 소스  

import java.sql.*;

public class Test07_selectAll {

    public static void main(String[] args) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
			
            String url     ="jdbc:oracle:thin:@localhost:1521:xe";
            String user    ="system";
            String password="1234";
            String driver  ="oracle.jdbc.driver.OracleDriver"; 
            Class.forName(driver);
            con =DriverManager.getConnection(url, user, password);		
            System.out.println("오라클 DB 서버 연결 성공");
			
            StringBuilder sql=new StringBuilder();
            sql.append(" SELECT sno, uname, kor, eng, mat, aver, addr, wdate ");
            sql.append(" FROM sungjuk ");
            sql.append(" ORDER BY sno DESC ");

            pstmt = con.prepareStatement(sql.toString());
            rs = pstmt.executeQuery();
            if(rs.next()) {//cursor가 있는지?
                System.out.println("자료있음");
                do {
                    System.out.print(rs.getInt("sno") + " ");
                    System.out.print(rs.getString("uname") + " ");
                    System.out.print(rs.getInt("kor") + " ");
                    System.out.print(rs.getInt("eng") + " ");
                    System.out.print(rs.getInt("mat") + " ");
                    System.out.print(rs.getInt("aver") + " ");
                    System.out.print(rs.getString("addr") + " ");
                    System.out.print(rs.getString("wdate") + " ");
                    System.out.println();
                }while(rs.next());	//다음 cursor가 있는지
            }else {
				System.out.println("자료없음");
			}
			
		} catch (Exception e) {
			System.out.println("오라클 DB 연결 실패 : " + e);
		} finally {//자원반납
            try {
                if(rs!=null) {rs.close();}
            } catch (Exception e) { }
			try {
                if(pstmt!=null) {pstmt.close();}
            } catch (Exception e) { }
            try {
                if(con!=null) {con.close();}
            } catch (Exception e) { }
        }
        
    }//main() end

}//class end

여러 행 가져오기 결과 (콘솔창)