Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

개발자 도전기

[Spring] JDBC로 데이터 등록하기 (INSERT INTO) 본문

개발공부/Spring

[Spring] JDBC로 데이터 등록하기 (INSERT INTO)

jnnjnn 2024. 4. 23. 00:36

 

INSERT INTO

INSERT INTO 해당테이블명 (컬럼명 ..)

데이터가 하나일 때는 VALUE, 여러 개일때는 VALUES를 사용하여 데이터를 나열한다

# INSERT INTO 테이블명 (컬럼명...)
# VALUES (데이터들...)

INSERT INTO Employees (LastName, FirstName, BirthDate, Photo, Notes)
VALUES ('captain', 'steve', '1990-01-01', 'pic1', 'america');

 

 

활용 예제

@Controller
@RequestMapping("main28")
public class Controller28 {
    @Autowired
    private DataSource dataSource;

	// main28/sub1으로 이동
    @GetMapping("sub1")
    public void sub1() {
    }

	// main28/sub1에서 form 제출받음
    @PostMapping("sub1")
    public String sub2(MyBean253Customer customer, RedirectAttributes rttr) throws Exception {
        Connection conn = dataSource.getConnection();

        String sql = """
                INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
                VALUES (?,?,?,?,?,?)
                """;
        PreparedStatement pstmt = conn.prepareStatement(sql);
        try (conn; pstmt) {
            pstmt.setString(1, customer.getCustomerName());
            pstmt.setString(2, customer.getContactName());
            pstmt.setString(3, customer.getAddress());
            pstmt.setString(4, customer.getCity());
            pstmt.setString(5, customer.getPostalCode());
            pstmt.setString(6, customer.getCountry());

            int rowCount = pstmt.executeUpdate();
            if (rowCount == 1) {
                rttr.addFlashAttribute("message", "새 고객이 등록되었습니다");
            }
        }
        // GET 방식으로 리다이렉트
        return "redirect:/main28/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>
<div>
    <c:if test="${not empty message}">
        <div style="padding: 20px ; background-color: skyblue">${message}</div>
    </c:if>
</div>
<h3>고객 정보 입력</h3>
<form action="" method="post">
    <div>
        이름
        <input type="text" name="customerName">
    </div>
    <div>
        계약명
        <input type="text" name="contactName">
    </div>
    <div>
        주소
        <input type="text" name="address">
    </div>
    <div>
        도시
        <input type="text" name="city">
    </div>
    <div>
        우편번호
        <input type="text" name="postalCode">
    </div>
    <div>
        국가
        <input type="text" name="country">
    </div>
    <div>
        <input type="submit" value="등록">
    </div>
</form>
</body>
</html>

 

@GetMapping과 @PostMapping

  • @GetMapping : 데이터 검색
  • @PostMapping : 데이터 생성 및 수정

executeUadate()는 DB에 대한 변경 작업을 실행할 때 사용 (INSERT, UPDATE, DELETE)

: 영향을 받은 레코드 수를 int로 반환한다

'개발공부 > Spring' 카테고리의 다른 글

[Spring] JDBC로 데이터 수정하기 (UPDATE)  (0) 2024.04.23
[Spring] JDBC로 데이터 삭제하기(DELETE)  (0) 2024.04.23
[STUDY] JDBC란?  (0) 2024.04.23
[Spring] 게시판 페이징 처리  (1) 2024.04.19
[Spring] Redirect  (0) 2024.04.18