[목차]
01. select 쿼리 실행을 위한 객체 생성 및 실행
💡
ResultSet rs = null;
rs = pstmt.executeQuery();
➡️ ResultSet 인터페이스 데이터 타입으로 rs 객체참조변수를 선언하고 null값으로 초기화 한다.
➡️ pstmt 객체참조변수에 할당된 주소를 찾아가서 메서드 영역 executeQuery() 메서드를 호출합니다.
pstmt 객체참조변수에 할당된 주소
👉🏻1️⃣ preparedStatement 인터페이스로 부터 명령받은 com.mysql.cj.jdbc.result패키지내 ClientPreparedStatement 클래스 통해 생성된 객체의 주소2️⃣ preparedStatement 인터페이스로 부터 명령받은 ClientPreparedStatement 클래스 통해 생성된 객체의 주소
3️⃣ preparedStatement 인터페이스 구현 객체 주소
➡️ 메서드를 호출하면 선언된 executeQuery 메서드 처리과정
- select 쿼리 실행 후 결과를 담고 응용 할 수 있는 ResultSet 구현객체를 생성한다.
ResultSet 객체 생성
👉🏻1️⃣ ResultSet 인터페이스로 부터 명령받은 com.mysql.cj.jdbc.result패키지내 ResultSetImpl 클래스 통해 생성된 객체 주소2️⃣ ResultSet 인터페이스로 부터 명령받은 ResultSetImpl 클래스 통해 생성된 객체의 주소
3️⃣ ResultSet 인터페이스 구현 객체 주소
- ResultSet 객체내에 쿼리 실행 결과를 담는다.
- ResultSet 구현객체 주소값을 메서드 호출한 곳으로 리턴한다.
- rs 객체참조변수에 주소값을 할당한다.
02. select 쿼리 실행결과 사용
💡
select 쿼리로 선택된 데이터를 화면에 출력할 수 있다.
[코드예제] while문
// rs.next() <- 리턴타입이 boolean이다. (true, false) // 데이터베이스에 저장된 행이 있다면 true / 없다면 false while(rs.next()) { // 출력할 컬럼 rs.getString("컬럼명1"); rs.getString("컬럼명2"); rs.getString("컬럼명3"); }
03. 회원전체조회 화면 구현
💡
1. 테이블 형식 조회 화면
2. JDBC 프로그램 실행 7단계
👉🏻
차이점
➡️ 쿼리 실행 준비 (insert, update, delete 와 다름)
➡️ 실행 결과 사용(select는 사용)
[코드예제] user_list.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <!DOCTYPE html> <%@ page import = "java.sql.DriverManager" %> <%@ page import = "java.sql.Connection" %> <%@ page import = "java.sql.PreparedStatement" %> <%@ page import = "java.sql.ResultSet" %> <%@ page import = "java.sql.SQLException" %> 회원리스트 <br/> <table width="100%" border="2"> <tr> <td>아이디</td> <td>비밀번호</td> <td>권한</td> <td>이름</td> <td>이메일</td> </tr> <% // 1단계 : 드라이버 로딩 Class.forName("com.mysql.jdbc.Driver"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { // 2단계 : DB연결 String jdbcDriver = "jdbc:mysql://localhost:3306/dbhooni?" + "useUnicode=true&characterEncoding=euckr"; String dbUser = "idhooni"; String dbPass = "pwhooni"; conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass); // 3단계 : 쿼리 실행을 위한 객체 생성 pstmt = conn.prepareStatement("SELECT * FROM tb_user"); // 4단계 : 쿼리 실행 rs = pstmt.executeQuery(); // System.out.println(rs.next()); // 5단계 : 쿼리 실행 결과 사용 while(rs.next()) { //System.out.println("반복횟수"); %> // html 시작 <tr> <td><%= rs.getString("u_id") %></td> <td><%= rs.getString("u_pw") %></td> <td><%= rs.getString("u_level") %></td> <td><%= rs.getString("u_name") %></td> <td><%= rs.getString("u_email") %></td> </tr> // html 끝 <% } } catch(SQLException ex) { out.println(ex.getMessage()); ex.printStackTrace(); } finally { // 6. 사용한 Statement 종료 if (rs != null) try { rs.close(); } catch(SQLException ex) {} if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {} // 7. 커넥션 종료 if (conn != null) try { conn.close(); } catch(SQLException ex) {} } %> </table>
tag : #mysql #DB #select #객체 #인터페이스 #쿼리 #while
Uploaded by N2T