
Connection 객체가 만들어지면, createStatement, prepareStatement 등과 같은 메서드를 통해서 Statement 객체를 생성할 수 있다.
Statement는 JDBC에서 실제 SQL 쿼리를 데이터베이스에 전송하고, 실행 결과를 반환받는 역할을 하는 객체이다.
Statement에는 크게 3가지로 나눌 수 있다.
Connection.createStatement()으로 Statement 객체 생성기본 Statement은 간단한 SQL문 실행에 사용된다.
매번 쿼리를 문자열로 전달해 실행하기 때문에, 매번 데이터베이스에서 쿼리 분석과 컴파일이 진행되어서 성능에 부담이 있따.
| 메서드 | 설명 |
|---|---|
| execute() | 질의문이나 갱신을 실행 |
| executeQuery() | SELECT 문을 실행한 후 ResultSet을 리턴 |
| executeUpdate() | INSERT, CREATE, DELETE 등을 실행 후 성공 개수를 int로 리턴 |
| close() | Statement 객체를 닫음 (자원 반환) |
| cancel() | 실행 중인 Statement를 취소 |
PreparedStatement은 SQL문을 미리 데이터베이스에 컴파일해 두고, 실행 시에는 파라미터만 바인딩 해서 실행하는 빠른 Statement이다.
?로 표시해두고, setString(), setInt() 통해서 값을 바인딩한다import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SimpleUpdateExample {
public static void main(String[] args) {
String no = "1"; // 예시: 수정할 글 번호
String title = "새 제목";
String contents = "새 내용";
String url = "jdbc:mysql://localhost:3306/project?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "1234";
String sql = "UPDATE board SET title=?, contents=? WHERE no=?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, title);
pstmt.setString(2, contents);
pstmt.setInt(3, Integer.parseInt(no));
int result = pstmt.executeUpdate();
if (result > 0) {
System.out.println("수정 성공");
} else {
System.out.println("수정 실패");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
위 예시 처럼
pstmt.setString(1, title);
pstmt.setString(2, contents);
pstmt.setInt(3, Integer.parseInt(no));
이 부분만 변경하면서 쿼리를 실행한다.
CallableStatement은 데이터베이스에 저장된 저장 프로시저를 호출할 때 사용하는 Statement이다.
복잡한 로직 전용이며, DB 내에서 미리 정의한 프로시저를 실행할 때 사용한다.
preparecall() 메서드를 통해서 생성한다.
간단한 예시...
CallableStatement cstmt = conn.prepareCall("{call procedure_name(?, ?)}");
cstmt.setInt(1, 100); // 입력값 바인딩
cstmt.registerOutParameter(2, java.sql.Types.INTEGER); // 출력값 등록
cstmt.execute();
int output = cstmt.getInt(2); // 출력값 얻기
cstmt.close();