SQL) INSERT INTO, executeQuery() 메소드
👉SPRING
@Controller
@RequestMapping("main28")
public class Controllere28 {
@Autowired
private DataSource dataSource;
@GetMapping("sub2")
public void sub2() {
}
@PostMapping("sub2")
public String sub2(MyBean254Employees employees, RedirectAttributes redirectAttributes) throws SQLException {
String sql = """
INSERT INTO Employees
(LastName, FirstName, BirthDate, Photo, Notes)
VALUES (?,?,?,?,?) ;
""";
Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
try (conn; pstmt) {
pstmt.setString(1, employees.getLastName());
pstmt.setString(2, employees.getFirstName());
pstmt.setDate(3, employees.getBirthDate());
pstmt.setString(4, employees.getPhoto());
pstmt.setString(5, employees.getNotes());
int row = pstmt.executeUpdate();
if (row == 1) {
redirectAttributes.addFlashAttribute("message", "새 고객이 등록되었습니다.");
}
}
return "redirect:/main28/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>
<div>
<c:if test="${not empty message}">
<div style="padding: 10px; background-color: burlywood">${message}</div>
</c:if>
</div>
<h2>새 직원 입력</h2>
<form action="" method="post">
<div>성
<input type="text" name="lastName">
</div>
<div>이름
<input type="text" name="firstName">
</div>
<div>생일
<input type="date" name="birthDate">
</div>
<div>사진
<input type="text" name="photo">
</div>
<div>특이사항
<input type="text" name="notes">
</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;
}
PreparedStatement 메소드
excuteQuery()
`executeQuery()` 메소드는 Java에서 JDBC(Java Database Connectivity)를 사용하여 데이터베이스에서 쿼리를 실행할 때 사용되는 메소드입니다. 이 메소드는 주어진 SQL 쿼리를 데이터베이스로 보내고, 그 결과로 `ResultSet` 객체를 반환합니다.
1. 사용법
`executeQuery()` 메소드는 `Statement` 또는 `PreparedStatement` 인터페이스를 구현한 객체에서 호출됩니다. 일반적으로는 `Connection` 객체를 통해 `createStatement()` 또는 `prepareStatement()` 메소드를 사용하여 `Statement` 또는 `PreparedStatement` 객체를 얻은 후에 `executeQuery()`를 호출합니다.
2. SQL 쿼리 실행
`executeQuery()` 메소드는 주어진 SQL 쿼리를 데이터베이스로 보내고 실행합니다. 이 메소드는 주로 `SELECT` 쿼리를 실행할 때 사용됩니다. `SELECT` 쿼리는 데이터베이스로부터 데이터를 조회하고 `ResultSet` 객체로 결과를 반환합니다.
3. 결과 반환
`executeQuery()` 메소드는 실행된 쿼리의 결과로 `ResultSet` 객체를 반환합니다. 이 `ResultSet` 객체는 쿼리의 실행 결과를 담고 있으며, 데이터베이스로부터 가져온 결과 집합을 효과적으로 조작하고 읽을 수 있도록 도와줍니다.
4. 주의 사항
- `executeQuery()` 메소드는 `SELECT` 쿼리와 같이 결과 집합을 반환하는 쿼리에서만 사용해야 합니다. 데이터를 조작하는 DML(Data Manipulation Language) 쿼리인 경우 `executeUpdate()` 메소드를 사용해야 합니다.
- SQL 쿼리에 오류가 있거나 실행에 실패한 경우 `SQLException`이 발생할 수 있습니다. 적절한 예외 처리를 해주어야 합니다.
DML(Data Manipulation Language) 쿼리인 경우 `executeUpdate()` 메소드를 사용
Math.min(int a, int b)
반환값 : the smaller of a and b