Notice
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- 2024겨울방학 코딩부트캠프
- transaction
- jsp
- 초등학생 겨울방학 놀이
- CSS
- Spring Security
- spring
- 뚜루뚜루
- js
- 초등학교 코딩수업
- 자바
- 이것이 자바다
- 핑퐁로봇
- 콜백함수
- 도서관 수업
- Cos Pro
- 알티노
- 자율주행자동차
- 코딩부트캠프
- 2023 ICT R&D 주간
- 스마트리움
- Java
- 은평구립도서관
- 초등학생 코딩수업
- 코딩수업
- 드론
- 2024우먼테크위크
- spring boot
- 서울시여성가족재단
- html
Archives
- Today
- Total
블로그
JDBC 작성 본문
✳️JDBC 순서
네트워크를 통해 데이터베이스와 연결을 맺고, SQL을 전달해 DB가 이를 실행하는 흐름
- 네트워크를 통해 DB와 연결을 맺는 단계
- DB에 보낼 SQL을 작성하고 전송하는 단계
- DB가 보낸 결과를 받아 처리하는 단계
- 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();
👉ResultSet은 SQL 결과를 저장한다.
1. Connection 객체로 DB연결
2. Query 실행을 위한 준비
- statement, PreparedStatement 객체 생성
3. Query 실행
ResultSet rs = pstmt.executeQuery();
int rowCount = pstmt.excuteUpdate();


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;
}
'개발자 준비과정 > Spring, SpringBoot, JSP' 카테고리의 다른 글
Post, Redirect, Get (PRG패턴) (0) | 2024.05.02 |
---|---|
transaction (0) | 2024.04.30 |
SQL) INSERT INTO, executeQuery() 메소드 (0) | 2024.04.19 |
Spring MVC, JDBC를 사용하여 페이징하기 (0) | 2024.04.19 |
<c:set> 태그 (0) | 2024.04.18 |