2019.02.01 JDBC: SQL문 사용하기 (SELECT)

2019. 2. 1. 16:48JSP

#1 SELECT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<%@page import="org.apache.catalina.Server"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JDBC SELECT</title>
</head>
<body>
    <h1>테이블 목록조회 테스트</h1>
    <table border="1">
        <tr>
            <th>도시이름</th><th>경도</th><th>위도</th>
        </tr>
        <%    /* STEP1 DB 연결 */
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "scott";
        String passwd = "tiger";
        
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        // DBSM과 연동
        // DBC 드라이버 로딩
        Class.forName("oracle.jdbc.OracleDriver");
        // DB연결
        con = DriverManager.getConnection(url, user, passwd);
        
        /* STEP2. SQL문 준비 */
        String sql = "SELECT* FROM location";
        // prepareStatement : sql문장 객체를 저장하는 문장객체
        pstmt = con.prepareStatement(sql); // sql문 전달
        
        
        /* STEP4. 실행 -> 실행결과를 ResultSet으로 가져온다 */
        rs = pstmt.executeQuery(); // DB서버로 sql문을 전달
        
        /* STEP5. 출력 -> 화면 출력 */
        while(rs.next()){ // 커서를 다음 행으로 이동후 ,행 유무를 boolean값으로 리턴
            String cityName    = rs.getString("city_name"); // 열이름 (city_name) 가져오기
            double longitude = rs.getDouble("longitude");
            double latitude = rs.getDouble("latitude");
            %>
            <tr>
                <td><%=cityName %></td>
                <td><%=longitude %></td>
                <td><%=latitude %></td>
            </tr>
            <%
        }//while
        
    %>
    </table>
    
    <% 
    // JDBC 자원 닫기(사용의 역순으로 닫음)
    rs.close();
    pstmt.close();
    con.close();
    %>
    
</body>
</html>
cs


>> 실행화면