본문 바로가기

Study/Java

Oracle JDBC 예제 코드(PrepareStatement)

반응형
public class JDBCTest {
    private static String query = "SELECT name, id, telephone FROM employee WHERE user_name = ?";

    // 형식 jdbc:oracle:<JDBC 드라이버>:@<IP>:<PORT>:<SID 또는 Service Name>
    // SID인 경우
    private static String URL = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";

    // Service Name인 경우
    private static String URL = "jdbc:oracle:thin:@127.0.0.1:1521/orcl";
    
    private static String USER = "ORACLE_USER";
    private static String PWD = "ORACLE_PWD";

    public static void main(String... args) {
        System.out.println("JDBC Test 시작");

        // 오라클 드라이버 로드
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("OracleDriver 클래스를 찾을 수 없습니다.");
            e.printStackTrace();
        }

        Connection connection =  null;
        PreparedStatement pstmt = null;
        ResultSet resultSet = null;
        try {
            // Connection 객체 생성
            connection = DriverManager.getConnection(URL, USER, PWD);

            // PrepareStatement 객체 생성
            pstmt = connection.prepareStatement(query);

            String targetName = "erinyees";

            // query에 ?로 된 값을 targetId(=erinyees)으로 치환
            pstmt.setString(1, targetId);

            // 쿼리 실행
            resultSet = pstmt.executeQuery();

            String name = null;
            String id = null;
            String telephone = null;
            while (resultSet.next()) {
                name = resultSet.getString("name");
                id = resultSet.getString("id");
                telephone = resultSet.getString("telephone");

                System.out.println("이름 : %s, 아이디 : %s, 전화번호 : %s ", name, id, telephone);
            }

        } catch (Exception e) {
            System.out.println("JDBC 예제를 실행할 수 없습니다.");
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (Exception ignore) {
                    resultSet = null;
                }
            }

            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (Exception ignore) {
                    pstmt = null;
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception ignore) {
                    connection = null;
                }
            }
        }

        System.out.println("JDBC Test 끝");
    }
}
  • 오라클 JDBC URL 생성시 SID, Service에 따른 차이 : 링크

  • 오라클 JDBC 드라이버 : 링크

반응형