개발공부/Spring

[Spring] JDBC로 데이터 삭제하기(DELETE)

jnnjnn 2024. 4. 23. 00:57

 

DELETE

DELET

FROM 테이블명

WHERE 조건

 

😵 WHERE을 쓰지 않으면 해당 테이블의 모든 레코드가 지워지니 주의

DELETE
FROM Employees
WHERE EmployeeID = 2039;

DELETE
FROM Employees
WHERE FirstName = 'natasha';

 

 

 

DELETE 사용해서 데이터 삭제하기

@Controller
@RequestMapping("main29")
public class Controller29 {
    @Autowired
    private DataSource dataSource;

	// 삭제할 데이터 조회 (GET)
    @GetMapping("sub1")
    public void method1(Integer id, Model model) throws Exception {
        if (id != null) {
            Connection conn = dataSource.getConnection();
            String sql = """
                    SELECT *
                    FROM Customers
                    WHERE CustomerId = ?
                    """;
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                MyBean253Customer c = new MyBean253Customer();
                c.setCustomerID(rs.getInt(1));
                c.setCustomerName(rs.getString(2));
                c.setContactName(rs.getString(3));
                c.setAddress(rs.getString(4));
                c.setCity(rs.getString(5));
                c.setPostalCode(rs.getString(6));
                c.setCountry(rs.getString(7));

                model.addAttribute("customer", c);
            }
        }
    }

	// 조회한 데이터 삭제 (POST)
    @PostMapping("sub1/delete")
    public String method2(Integer id, RedirectAttributes rttr) throws Exception {
        String sql = """
                DELETE FROM Customers
                WHERE CustomerID = ?
                """;
        Connection conn = dataSource.getConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, id);
        
        try (conn; pstmt) {
            int rowCount = pstmt.executeUpdate();
            if (rowCount > 0) {
            // 리다이렉트 시에도 데이터 유지되게 RedirectAttribute 객체 사용
                rttr.addFlashAttribute("message", id + " 번 고객이 삭제되었습니다");
            } else {
                rttr.addFlashAttribute("message", "삭제되지 않았습니다");
            }
        }
        // GET 방식으로 리다이렉트
        return "redirect:/main29/sub1";

    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyBean253Customer {
    private Integer customerID;
    private String customerName;
    private String contactName;
    private String address;
    private String city;
    private String postalCode;
    private String country;
}
<%@ 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: pink; padding: 20px">
            ${message}
    </div>
</c:if>
<h3>고객 조회</h3>
<form action="">
    고객번호
    <input type="number" name="id">
    <button>조회</button>
</form>
<hr>
<c:if test="${empty customer}">
    조회된 고객이 없습니다
</c:if>
<c:if test="${not empty customer}">
    <div>
        번호
        <input type="number" readonly value="${customer.customerID}">
    </div>
    <div>
        이름
        <input type="text" readonly value="${customer.customerName}">
    </div>
    <div>
        계약명
        <input type="text" readonly value="${customer.contactName}">
    </div>
    <div>주소
        <input type="text" readonly value="${customer.address}">
    </div>
    <div>도시
        <input type="text" readonly value="${customer.city}">
    </div>
    <div>우편번호
        <input type="text" readonly value="${customer.postalCode}">
    </div>
    <div>국가
        <input type="text" readonly value="${customer.country}">
    </div>
    <form action="/main29/sub1/delete" method="post" onsubmit="return confirm('삭제하시겠습니까?')">
        <div style="display: none">
            <input type="text" name="id" value="${customer.customerID}">
        </div>
        <div>
            <button style="background-color: rosybrown">삭제</button>
        </div>
    </form>
</c:if>
</body>
</html>

 

GET 방식으로 조회한 데이터를 POST 방식으로 전송하여 쿼리문을 통해 DB에서 삭제하게 했다

 

form의 onsubmit 이벤트 핸들러로 삭제 버튼을 눌렀을 때

자바스크립트 브라우저 내장함수인 confirm()을 리턴해서 확인/취소 대화상자가 나타나게 만들었다