개발자 도전기
[STUDY] JDBC란? 본문
JDBC란?
JDBC(Java Database Connectively)는 Java 기반 어플리케이션의 데이터를 데이터베이스를 연결시켜주는 자바 API이다. JDBC는 데이터베이스 제작업체에서 제공하는 드라이버를 사용하여 데이터베이스에 엑세스할 수 있도록 한다
JDBC는 3가지 기능을 표준 인터페이스로 정의하여 제공한다
- java.sql.Connection - 연결
- java.sql.Statement - SQL을 담은 내용
- java.sql.ResultSet - SQL 요청 응답
JDBC의 동작 흐름
JDBC 드라이버
- 데이터베이스와의 통신을 담당하는 인터페이스
- Oracle, MySQL 등과 같은 데이터베이스에 알맞은 JDBC 드라이브를 구현하여 제공
- JDBC 드라이버의 구현체를 이용하여 특정 벤더의 데이터베이스에 접근할 수 있음
JDBC API의 사용 흐름
1. Connection 객체 생성
String url = "jdbc:mariadb://localhost:3306/w3schools";
String user = "root";
String password = "****";
Connection con = DriverManager.getConnection(url, user, password);
사용하고자 하는 JDBC 드라이버를 DriverManager를 통해 불러와 Connection 객체를 생성한다.
Datasource를 빈으로 DB 정보를 저장해놓으면 Datasource 빈만 주입할 수 있다
@Autowired
private DataSource dataSource;
...
Connection conn = dataSource.getConnection();
2. Statement 객체 생성
Statement stmt = conn.createStatement();
Statement 객체는 작성된 SQL 쿼리문을 실행하기 위한 객체로 정적 SQL 쿼리 문자열을 입력으로 가진다
Statement 인터페이스를 상속받은 인터페이스로는 PreparedStatement가 있다
3. Qurey 실행
ResultSet rs = stmt.executeQuery(sql);
쿼리를 실행하고 결과로 ResultSet 객체를 받는다.
4. ResultSet 객체로부터 데이터 조회 및 사용한 객체 닫기
try (conn; stmt; rs) {
while (rs.next()) {
MyBean241 bean = new MyBean241();
bean.setFirstName(rs.getString(1));
bean.setLastName(rs.getString(2));
list.add(bean);
}
}
ResultSet은 쿼리의 결과를 행으로 저장하며 커서를 통해서 각 행의 데이터에 접근한다. 최초의 커서는 1행 이전에 존재하게 된다. next() 메소드는 커서의 다음 행이 존재할 경우 true를 리턴하고 커서를 그 행으로 이동시킨다. 마지막 행에 커서가 도달하면 false를 리턴한다
rs.next()로 모든 행을 읽을 때까지 가져온 결과값을 bean에 담는다
getString()은 해당 행의 컬럼의 인덱스 값을 넣어 값을 가져온다. String을 반환하며 getInt는 int를 반환한다
사용이 끝난 객체들은 try-with-resources를 사용하여 닫아준다
5. 모델 객체에 결과 담기
1) employee 속성에 list 값을 추가한다
model.addAttribute("employees", list);
2) @ModelAttribute를 사용하여 바인딩한다
@ModelAttribute("employees") ArrayList<MyBean241> list
6. view로 포워드하기
해당 메소드의 경로에 대응하는 jsp 파일을 작성한다
사용 예제
SELECT 문으로 데이터 조회 및 view로 출력
@Controller
@RequestMapping("main24")
public class Controller{
@GetMapping("sub2")
public void method2(@ModelAttribute("customers") ArrayList<MyBean242> list) throws Exception {
String sql = """
SELECT CustomerName, City, Country
FROM Customers
""";
Connection conn = dataSource.getConnection();
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
try (conn; statement; rs) {
while (rs.next()) {
MyBean242 bean = new MyBean242();
bean.setCustomerName(rs.getString(1));
bean.setCity(rs.getString(2));
bean.setCountry(rs.getString(3));
list.add(bean);
}
}
}
}
@Data
public class MyBean242 {
private String customerName;
private String city;
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>
<h3>Customers</h3>
<table>
<thead>
<tr>
<th>#</th>
<th>CustomerName</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer" varStatus="status">
<tr>
<td>${status.count}</td>
<td>${customer.customerName}</td>
<td>${customer.city}</td>
<td>${customer.country}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
'개발공부 > Spring' 카테고리의 다른 글
[Spring] JDBC로 데이터 삭제하기(DELETE) (0) | 2024.04.23 |
---|---|
[Spring] JDBC로 데이터 등록하기 (INSERT INTO) (0) | 2024.04.23 |
[Spring] 게시판 페이징 처리 (1) | 2024.04.19 |
[Spring] Redirect (0) | 2024.04.18 |
[Spring] PreparedStatement를 이용해서 데이터베이스 출력하기 (0) | 2024.04.17 |