프로그래밍/JSP

[쉽게 배우는 JSP 웹 프로그래밍 개정2판] 16장 연습 문제, 소스 코드

곰탱이들 2024. 6. 9.

16장 연습 문제 소스 코드

16장 연습 문제

 

1. JDBC를 사용한 JSP와 데이터베이스를 연동하는 기법을 단계별로 나열한 것으로 옳은 것은 무엇인가?

  • 1번 ② ① ⑤ ④ ③ ⑦ ⑥

 

2. Statement 객체와 PreparedStatement 객체의 메소드이면서 데이터베이스로부터 검색 SQL문 쿼리를 실행하여 데이터 접근을 할 수 있는 메소드는 무엇인가?

  • 1번 executeQuery()

 

3. JDBC 드라이버를 로딩하는 메소드는 무엇인가?

  • 1번 Class.forName()

 

4. Statement 객체와 PreparedStatement 객체의 메소드이면서 데이터베이스로부터 삽입, 수정, 삭제와 관련된 SQL문 쿼리를 실행하여 데이터 접근을 할 수 있는 메소드는 무엇인가?

  • 2번 executeUpdate()

 

5. 데이터베이스로부터 쿼리문의 실행 결과 값을 가져오는 ResultSet 객체의 메소드로 옳지 않은 것은 무엇인가?

  • 4번 end()

 

6. 데이터베이스로부터 쿼리문의 실행 결과 값을 가져오는 ResultSet 객체의 메소드 중 에서 설정한 row 행으로 커서를 이동하는 메소드는 무엇인가?

  • 4번 absolute()

소스 코드

7

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student List</title>
</head>
<body>
    <h2>Student List</h2>
    <table>
        <tr>
            <th>학번</th>
            <th>학과</th>
            <th>이름</th>
            <th>주소</th>
            <th>연락처</th>
        </tr>
        <%
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                
                String dbURL = "jdbc:mysql://localhost:3306/your_database";
                String dbUser = "//DB 아이디";
                String dbPassword = "//DB 비밀번호";
                conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);

                String sql = "SELECT student_id, department, name, address, contact FROM Student";
                pstmt = conn.prepareStatement(sql);

                rs = pstmt.executeQuery();

                while (rs.next()) {
                    String studentId = rs.getString("student_id");
                    String department = rs.getString("department");
                    String name = rs.getString("name");
                    String address = rs.getString("address");
                    String contact = rs.getString("contact");
        %>
        <tr>
            <td><%= studentId %></td>
            <td><%= department %></td>
            <td><%= name %></td>
            <td><%= address %></td>
            <td><%= contact %></td>
        </tr>
        <%
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (rs != null) try { rs.close(); } catch (SQLException e) { e.printStackTrace(); }
                if (pstmt != null) try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
                if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
            }
        %>
    </table>
</body>
</html>

 

 

8

CREATE DATABASE ExerciseDB;

USE ExerciseDB;

CREATE TABLE Student (
    student_id VARCHAR(20) PRIMARY KEY,
    department VARCHAR(50),
    name VARCHAR(50),
    address VARCHAR(100),
    contact VARCHAR(20)
);

INSERT INTO Student (student_id, department, name, address, contact) VALUES 
('202310001', '모바일과', '홍길순', '서울시', '010-9002-1234'),
('202310002', '모바일과', '홍길동', '경기도', '010-2009-4321');
('202320001', '영어과', '수여인', '인천시', '010-3918-0007');
('202320002', '영어과', '김다운', '서울시', '010-3002-0101');

 

insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert Student</title>
</head>
<body>
    <h2>Database SQL</h2>
    <form action="insert_process.jsp" method="post">
        <label for="studentId">학번:</label>
        <input type="text" id="studentId" name="studentId" required><br><br>
        <label for="department">학과:</label>
        <input type="text" id="department" name="department" required><br><br>
        <label for="name">이름:</label>
        <input type="text" id="name" name="name" required><br><br>
        <label for="address">주소:</label>
        <input type="text" id="address" name="address" required><br><br>
        <label for="contact">연락처:</label>
        <input type="text" id="contact" name="contact" required><br><br>
        <input type="submit" value="전송">
    </form>
</body>
</html>

 

insert_process.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%
    String studentId = request.getParameter("studentId");
    String department = request.getParameter("department");
    String name = request.getParameter("name");
    String address = request.getParameter("address");
    String contact = request.getParameter("contact");

    Connection conn = null;
    PreparedStatement pstmt = null;

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String dbURL = "jdbc:mysql://localhost:3306/ExerciseDB";
        String dbUser = "//DB 아이디 입력";
        String dbPassword = "//DB 비밀번호 입력";
        conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);

        String sql = "INSERT INTO Student (student_id, department, name, address, contact) VALUES (?, ?, ?, ?, ?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, studentId);
        pstmt.setString(2, department);
        pstmt.setString(3, name);
        pstmt.setString(4, address);
        pstmt.setString(5, contact);

        int rows = pstmt.executeUpdate();

        if (rows > 0) {
            out.println("A new student has been inserted successfully.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (pstmt != null) try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); }
        if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }
    }
%>

댓글