하늘바람a 2024. 4. 22. 17:49

✳️JDBC 순서

네트워크를 통해 데이터베이스와 연결을 맺고, SQL을 전달해 DB가 이를 실행하는 흐름

 

  1. 네트워크를 통해 DB와 연결을 맺는 단계
  2. DB에 보낼 SQL을 작성하고 전송하는 단계
  3. DB가 보낸 결과를 받아 처리하는 단계
  4. DB와 연결을 종료하는 단계

 

1.Connection conn = data.getConnection();

// Connection 객체로 DB 연결
Connection conn = dataSource.getConnection();

 

2. String sql = "SQL문";

PreparedStatement pstmt = conn.prepareStatement(sql);

// SQL문 생성
String sql = "SELECT * FROM Employees WHERE EmployeeId = ?";
// Query 실행을 위해 객체생성
PreparedStatement pstmt = conn.prepareStatement(sql);
// SQL문의 ? 에 어떤 값을 넣을지 정하기
pstmt.setString(1, id);

 

4.ResultSet rs = pstmt.excuteQuery();

// SELECT문
ResultSet rs = pstmt.executeQuery();
// INSERT, UPDATE, DELETE 문
int rowCount = pstmt.excuteUpdate();

 

👉ResultSetSQL 결과를 저장한다.

 

1. Connection 객체로 DB연결

2. Query 실행을 위한 준비

- statement, PreparedStatement 객체 생성

3. Query 실행

ResultSet rs = pstmt.executeQuery();

int rowCount = pstmt.excuteUpdate();

 

 

직원 조회
UPDATE 수행

 

Spring

@Controller
@RequestMapping("main30")
public class Controller30 {
    @Autowired
    private DataSource dataSource;

    // todo : 직원 조회 및 수정
    @GetMapping("sub2")
    public void method2(String id, MyBean254Employees e, Model model) throws SQLException {
        if (id != null) {
            String sql = """ 
                        SELECT * FROM Employees WHERE EmployeeId = ?
                    """;
            Connection conn = dataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            ResultSet rs = pstmt.executeQuery();
            try (conn; pstmt; rs) {
                if (rs.next()) {
                    e.setEmployeeID(rs.getString(1));
                    e.setLastName(rs.getString(2));
                    e.setFirstName(rs.getString(3));
                    e.setBirthDate(rs.getDate(4));
                    e.setPhoto(rs.getString(5));
                    e.setNotes(rs.getString(6));

                    model.addAttribute("employee", e);
                }
            }
        }
    }


    @PostMapping("sub2/update")
    public String update2(RedirectAttributes rttr, MyBean254Employees e) throws SQLException {
        String sql = """
                UPDATE Employees 
                SET LastName=?,
                    FirstName=?,
                    BirthDate=?,
                    Photo=?,
                    Notes=?
                WHERE EmployeeId=?
                """;
        Connection conn = dataSource.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);

        try (conn; pstmt) {
            pstmt.setString(1, e.getLastName());
            pstmt.setString(2, e.getFirstName());
            pstmt.setDate(3, e.getBirthDate());
            pstmt.setString(4, e.getPhoto());
            pstmt.setString(5, e.getNotes());
            pstmt.setString(6, e.getEmployeeID());

            int rowCount = pstmt.executeUpdate();

            if (rowCount > 0) {
                // 모델에 붙음
                rttr.addFlashAttribute("message", e.getEmployeeID() + "번 직원 정보가 업데이트되었습니다.");
            } else {
                rttr.addFlashAttribute("message", "수정되지 않았습니다.");
            }
        }
        // 쿼리스트링에 붙음
        rttr.addAttribute("id", e.getEmployeeID());
        return "redirect:/main30/sub2";
    }
}

 

👉JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:if test="${not empty message}">
    <div style="background-color: mediumaquamarine">${message}</div>
</c:if>
<h3>직원 정보 조회</h3>
<form action="">
    <input type="number" name="id">
    <button>조회</button>
</form>
<hr>
<h4>${employee.employeeID}번 직원 조회</h4>
<form action="/main30/sub2/update" method="post">
    <%--    위에 있는 *번 직원 조회를 쓰려면 name 지정해줘야 함--%>
    <%--    name을 자바빈의 이름으로 해주어야 함.--%>
    <input type="hidden" name="employeeID" value="${employee.employeeID}">
    <div>성
        <input type="text" name="lastName" value="${employee.lastName}">
    </div>
    <div>이름
        <input type="text" name="firstName" value="${employee.firstName}">
    </div>
    <div>생일
        <input type="date" name="birthDate" value="${employee.birthDate}">
    </div>
    <div>사진
        <input type="text" name="photo" value="${employee.photo}">
    </div>
    <div>상세 사항
        <br>
        <textarea name="notes" id="" cols="30" rows="10">${employee.notes}</textarea>
    </div>
    <div>
        <input type="submit" value="수정">
    </div>
</form>
</body>
</html>

 

 

👉자바빈

import lombok.Data;
import java.sql.Date;

@Data
public class MyBean254Employees {
    private String employeeID;
    private String lastName;
    private String firstName;
    private Date birthDate;
    private String photo;
    private String notes;
}