728x90
목차
JDBC
https://shs2810.tistory.com/18
https://devlog-wjdrbs96.tistory.com/139
JDBC = Java Database Connectivity
자바와 데이터베이스를 연결해서 데이터를 주고 받게 해주는 프로그래밍 인터페이스
각 DBMS에 맞는 드라이버가 필요함!
작업 순서
- JDBC 사용 (Driver Loading)
- DB 연결 (Connection 생성)
- SQL 준비 및 실행
- DB 연결 해제 (종료)
1. JDBC 사용 (Driver Loading)
Class.forName("com.mysql.Jdbc.Driver");
2. DB 연결 (connection)
String url = "jdbc:mysql://localhost:3306/board?serverTimezone=UTC";
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
localhost:3306 = 로컬 환경에서 MySQL의 포트 번호
board : 가져오려는 schema 이름
username과 password는 MySQL에서의 username과 password
이 과정을 통해 연결 가능
3. SQL 준비 및 실행
1. Statement + SELECT
Statement stmt = con.createStatement();
String sql = "SELECT * from board";
ResultSet result = stmt.executeQuery(sql);
conn = util.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
Board board = new Board();
board.setId(rs.getInt("id"));
board.setTitle(rs.getString("title"));
}
rs.getString
, rs.getInt
= column의 index 또는 column의 label 이름으로 데이터를 가져올 수 있음
rs.next()
: DB의 row 한 줄을 불러옴, false일 경우 더 이상 불러올 row가 없다는 뜻
2. PreparedStatement + UPDATE / DELETE / INSERT
예시는 insert
String sql = "INSERT INTO board (id, title, content) VALUES (?,?,?)";
Connection conn = util.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getId());
pstmt.setString(2, board.title());
pstmt.setString(3, board.getContent());
int result = pstmt.executeUpdate(); // 영향 받은 row의 개수
System.out.println(result);
pstmt.setString(parameterIndex, x)
= ‘?’의 순서에 따라 x값을 할당해줌executeUpdate()
: 테이블의 내용을 변경하는 문장에 사용(create, drop, insert, delete, update)- 영향받은 row의 개수를 반환, 아무 것도 반환하지 않으면 0
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
[참고] Statement와 PreparedStatement의 차이?
https://flatsun.tistory.com/386
https://devbox.tistory.com/entry/Comporison
- Statement
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(sql);
- createStatement 메소드에 파라미터가 없다.
- 실행 전까지는 무슨 쿼리를 실행하는지 알 수 없음 (executeQuery의 매개변수로 sql을 넣음)
- 쿼리문을 실행할 때마다 생성하며 반복 실행되는 경우에 효율이 떨어짐 (수행하는 과정에서 매번 컴파일)
- 쿼리문을 프로그램 외부에서 작성한 뒤 내부에서 실행하는 SQL Injection 공격에 취약
- 전달되는 SQL문은 완성된 형태 → 한눈에 파악하기 쉬움
- PreparedStatement
String sql = "SELECT * FROM board WHERE id =?"; // ? -> 미완성
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery(); // 실행 시 매개변수 x
- ‘?’ = Bind 변수, 값을 가변적으로 바꿀 때 사용
- 쿼리문을 미리 생성함 (
prepareStatement()
메소드를 통해) - 쿼리를 파라미터에 넣지 않고 수행 → 실행시마다 쿼리를 생성하지 않아서 속도가 빠름
- Bind 변수로 인해 SQL문이 완성된 형태가 아님 → 한눈에 파악하기 어려움
4. DB 연결 해제
Connection, Statement, ResultSet에 대해 close
public static void close(Connection conn, PreparedStatement pstmt) {
try {
if(pstmt != null) {
pstmt.close();
}
}catch (Exception e) {
e.getStackTrace();
}
try {
if(conn != null) {
conn.close();
}
}catch (Exception e) {
e.getStackTrace();
}
}
/**
* 사용한 리소스들을 정리한다. Connection, Statement, PreparedStatement, ResultSet 모두
* AutoCloseable 타입 ... 을 이용하므로 필요에 한번에 정리가능
*
* @param autoCloseables
*/
public void close(AutoCloseable... autoCloseables) {
for (AutoCloseable ac : autoCloseables) {
if (ac != null) {
try {
ac.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
728x90
'CS > DataBase' 카테고리의 다른 글
[데이터베이스 개론] 5. 관계 데이터 모델 (1) | 2022.09.29 |
---|---|
[데이터베이스 개론] 4. 데이터 모델링 (0) | 2022.09.27 |
[데이터베이스 개론] 3. 데이터베이스 시스템 (0) | 2022.09.24 |
[데이터베이스 개론] 2. 데이터베이스 관리 시스템 (1) | 2022.09.20 |
[데이터베이스 개론] 1. 데이터베이스 기본 개념 (0) | 2022.09.19 |