개발공부/Spring
[Spring] PreparedStatement를 이용해서 데이터베이스 출력하기
jnnjnn
2024. 4. 17. 21:27
PreparedStatement
- JDBC의 인터페이스 중 하나이다
- SQL 쿼리의 일부를 동적으로 바꿀 수 있다
- 입력 매개변수를 안전하게 처리할 수 있다 - setString() 메소드 사용
Statement가 아닌 PreparedStatement를 사용하는 이유
- 인자값으로 전달이 가능하다
- 가독성이 높다
- SQL Injection을 방지할 수 있다
PreParedStatement 사용 방법
쿼리문의 매개변수 자리에 ?를 넣어준다
String sql = """
SELECT *
FROM Products
WHERE ProductName = ?
""";
setString()으로 ? 자리를 매개변수로 대체한다
여기서 setString()의 첫번째 인자값은 ?의 순서, 해당 ? 위치에 대입할 값이다
Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
// 첫번째 파라미터 : 물음표 위치
// 두번째 파라미터 : 넣을 값
pstmt.setString(1, search);
ResultSet rs = pstmt.executeQuery();
? 가 여러개라면 ?의 갯수만큼 setString() 메소드를 사용한다.
입력값을 받아 해당하는 데이터베이스를 출력하는 예제
@GetMapping("sub8")
public String method(String name, Model model) throws Exception {
var list = new ArrayList<MyBean255Employee>();
// LastName과 FirstName에
// @requestParam name이 포함되는 Employees 데이터베이스 가져오기
String sql = """
SELECT *
FROM Employees
WHERE LastName LIKE ?
OR FirstName LIKE ?
""";
String keyword = "%" + name + "%";
Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
// ? 를 keyword로 대체
pstmt.setString(1, keyword);
pstmt.setString(2, keyword);
ResultSet rs = pstmt.executeQuery();
try (pstmt; rs; conn) {
// 데이터베이스가 없을 때까지
while (rs.next()) {
// 데이터베이스 값 자바빈에 담기
String id = rs.getString(1);
String last = rs.getString(2);
String first = rs.getString(3);
String birth = rs.getString(4);
String photo = rs.getString(5);
String notes = rs.getString(6);
MyBean255Employee row = new MyBean255Employee(id, last, first, birth, photo, notes);
// 자바빈을 리스트에 담기
list.add(row);
}
}
// 모델에 리스트 추가
model.addAttribute("employees", list);
return "main25/sub8EmployeesList";
}
@Data
@AllArgsConstructor
public class MyBean255Employee {
private String employeeID;
private String lastName;
private String firstName;
private String birthDate;
private String photo;
private String notes;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>직원 목록 검색</h4>
<style>
tr,
table,
td,
th {
border: 1px solid black;
padding: 2px;
justify-content: center;
}
</style>
<form action="">
// 검색할 Employee 이름 입력값 받기
<input value="${param.name}" type="text" name="name" placeholder="이름을 입력하세요">
<button>입력</button>
</form>
<c:if test="${empty employees}" var="emptyEmployees">
해당 직원이 없습니다
</c:if>
<c:if test="${not emptyEmployees}">
<table>
<thead>
<tr>
<th>ID</th>
<th>LastName</th>
<th>FirstName</th>
<th>BirthDate</th>
<th>Photo</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<c:forEach items="${employees}" var="employee">
<tr>
<td>${employee.employeeID}</td>
<td>${employee.lastName}</td>
<td>${employee.firstName}</td>
<td>${employee.birthDate}</td>
<td>${employee.photo}</td>
<td>${employee.notes}</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</body>
</html>