일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 티스토리챌린지
- q87
- wsdl
- 톰캣
- ibatis
- cmd
- java
- SID
- letterspacing
- httpservletreqeust
- Docker
- servicename
- 키보드
- MariaDB
- 영상편집
- API
- service name
- 프로세스
- 스레드 덤프
- HTML
- 컨트롤러
- 안드로이드 스튜디오
- http
- MySQL
- oracle
- JDBC
- Database
- 스레드
- Tomcat
- 오블완
- Today
- Total
블로그 이름
[JAVA] JDBC의 Connection, Statement, ResultSet 본문
우선 가볍게 JDBC가 무엇인지?
JDBC(Java Database Connectivity)는 Java 기반 애플리케이션의 데이터를 데이터베이스에 저장 및 업데이트하거나, 데이터베이스에 저장된 데이터를 Java 에서 사용할 수 있도록 하는 자바 API이다.
JDBC는 3가지 기능을 표준 인터페이스로 정의하여 제공한다.
java.sql.Connection은 연결, Statement는 SQL전달, ResultSet은 결과 응답
JDBC API 사용 흐름은 아래와 같다.
1. JDBC 드라이버 로딩
2. Connection 객체 생성
3. Statement 객체 생성
4. query 실행
5. resultSet 객체로부터 데이터 조회
6. ResultSet 객체 close
7. statement 객체 close
8. connection 객체 close
JDBC 드라이버 로딩 후 사용하고자 하는 JDBC 드라이버를 로딩 후, Connection 객체를 생성한다. (세션)
statement 객체로 작성한 쿼리문을 입력하며, query를 statement객체로 실행한다.
이후 resultset 객체로부터 실행된 sql 쿼리문에 대한 결과를 받아온다.
이후, 역순으로 close한다
Connection, Statement, ResultSet 닫는 방법
public class Class1 {
public method1() throws Exception {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = ...;
ps = ...;
rs = ...;
} catch (Exception e) {
//
} finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (ps != null) try { ps.close(); } catch(Exception e) {}
if (conn != null) try { conn.close(); } catch(Exception e) {}
}
}
}
Java 7 에서 AutoCloseable 인터페이스와 try-with-resources 가 등장했다.
try-with-resources 를 사용하여 JDBC API 사용하는 코드를 개선할 수 있다.. try 블록의 소괄호 () 안에서 close() 메서드 호출이 필요한 (AutoCloseable 를 구현한) 객체를 할당해 주면 된다.
try catch 절이 종료되면 객체의 close() 메서드가 자동으로 호출된다.
public class Class1 {
public method1() throws Exception {
try (Connection conn = DriverManager.getConnection("...");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT 1 from dual")) {
// ...
} catch (Exception e) {
// ...
}
}
}
Java 7 에서 try-with-resources 를 사용할 때 close() 메서드 자동 호출을 위해 꼭 try 블록의 소괄호 안에서 자원 할당을 해야만 했다.
하지만 Java 9 부터는 try-with-resources 를 좀 더 유연하게 사용할 수 있게 되어서 try 블록의 밖에서 선언된 객체를 참조할 수 있다.
public class Class1 {
public method1() throws Exception {
Connection conn = DriverManager.getConnection("...");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT 1 from dual")
try (conn; stat; rs) {
// ...
} catch (Exception e) {
// ...
}
}
}
'개발 > Java' 카테고리의 다른 글
[JPA] Java Persistance API 란 (0) | 2025.02.25 |
---|---|
[JAVA] Reflection API (0) | 2025.02.19 |
[JAVA] Java 및 cmd 기본 명령어 (1) | 2025.02.12 |
[JAVA] 자바 버전별 차이 및 특징 (8, 11, 17, 21) (0) | 2025.02.12 |
[JAVA] 자바 버전 여러 개 활용하기 (프로그램 실행 시 자바 버전 변경) (0) | 2025.02.12 |