본문 바로가기
Backend/Java & SQL

자바에서 PreparedStatement 알아보기

by Dreamvelope 2024. 5. 7.

회사 들어오고나서 생전 처음해보는 자바로 백엔드를 짜야한다.

 

다시한번 Python, JavaScript 의 자유분방함에 감사를 느끼는 일주일이 되고있다.

 

ArrayList 와 그냥 Array의 구분, 그리고 구분된것마다 사용되는 다른 method,  여러 클래스들의 반환타입 등등등등등등

 

외워야 할게 한두개가 아니다...

 

하지만 이렇게 디테일하게 나눠놓은 덕분에 성능 최적화에 특화된 느낌이긴하다.

 

pstmt 를 사용한 SQL구문 예시를 처음 보고 사용해보는데 기본적인 자바 문법도 잘 모르니 정말 어지러운 일주일이었다.

 

# PreparedStatement란?

 

PreparedStatement은 데이터베이스 쿼리를 실행하기 전에 미리 컴파일된 SQL 문을 나타내는 인터페이스.

Java에서 주로 사용되며, SQL 쿼리의 파라미터화된 버전을 나타낸다고한다.

이를 통해 SQL 쿼리를 실행할 때마다 새로운 쿼리를 생성하는 대신, 쿼리의 구조를 한 번만 정의하고 나중에 매개 변수를 채워넣을 수 있다.

 

```import java.sql.*;

public class Example {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            // 데이터베이스 연결
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/exampleDB", "username", "password");
            
            // PreparedStatement 생성
            String sql = "SELECT * FROM users WHERE username = ?";
            preparedStatement = connection.prepareStatement(sql);
            
            // 파라미터 설정
            preparedStatement.setString(1, "exampleUsername");
            
            // 쿼리 실행 및 결과 얻기
            resultSet = preparedStatement.executeQuery();
            
            // 결과 처리
            while (resultSet.next()) {
                // 결과 처리
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 리소스 해제
            try {
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
```

 

예시 구문

 

일단 pstmt 에 문자열로 된 쿼리를 연결시킨다. 

 

pstmt = "SELECT * FROM users WHERE username = ?"

 

저기에 들어있는 ? 가 pstmt를 쓰는 핵심인거같은데 ? 는 동적으로 문자열을 바꿀 수 있는 하나의 '칸'이라고 보면된다.

 

 

 

댓글


반갑습니다 ✿ڿڰۣ— 조은하루 ^^
SSAFY 9기 김웅서 티스토리