JDBC Programming

2024. 11. 3. 17:28데이터 분석/데이터 베이스 프로그래밍

import java.sql.*;

java.sql package를 import함!

public class Lab3{

CLASS 구성 시작!

생성자

    public Lab3(){ // 생성자
        // JDBC 드라이버 로딩
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }catch(ClassNotFoundException ex){
            ex.printStackTrace();
        }
    }

Class.forName(DRIVER_CLASS_NAME)

해당하는 클래스를 runtime에 동적으로 로딩

  • 클래스 이름은 프로그램에서 문자열로 지정 (변경 가능)

메모리에 Driver 객체를 생성하고 DriverManager 객체에 등록함

JDBC Driver 클래스 예

  • Oracle: oracle.jdbc.driver.OracleDriver
  • MySQL: com.mysql.jdbc.Driver 또는 org.gjt.mm.mysql.Driver

연결 설정

    private static Connection getConnection(){
        String url = "jdbc:oracle:thin:@link:1234/orclpdb";
        String user = "dbp2024";
        String passwd = "PASWD";

        // DBMS와의 연결 생성
        Connection conn = null;
        try{
            conn=DriverManager.getConnection(url,user,passwd);
        }catch(SQLException e){
            e.printStackTrace();
        }
        return conn;
    }

StmtEx.java

package jdbc.examples;
import java.sql.*; // 1. JDBC 관련 package import
public class StmtEx {
public static void main(String args[]) 
{
	Connection conn = null;
	Statement stmt = null;
	ResultSet rs = null;
	String url = "jdbc:oracle:thin:@localhost:1521/xepdb1";
	String user = "scott", passwd = "TIGER";
	try {
		Class.forName("oracle.jdbc.driver.OracleDriver"); // 2. JDBC Driver 로딩 및 등록
	} catch (ClassNotFoundException ex) { 
    ex.printStackTrace(); 
    } try {
		conn = DriverManager.getConnection(url, user, passwd); // 3. DBMS와의 연결
		// 획득
		String query = "SELECT * FROM EMP WHERE DEPTNO = 10";
		stmt = conn.createStatement(); // 4. SQL문을 위한 Statement 객체 생성
		rs = stmt.executeQuery(query); // 5. Statement 객체를 사용하여 SQL문 실행
		System.out.println("EmpNo Name");
		while (rs.next()) { // 6. DBMS 응답 사용
		int no = rs.getInt("EMPNO");
		String name = rs.getString("ENAME");
		System.out.println(no + " " + name);
			}
		} catch (SQLException ex) { ex.printStackTrace(); } 
		finally { // 7. 자원 반납
			if (rs != null) {
				try { rs.close(); } catch (SQLException ex) { ex.printStackTrace(); }
			}
			if (stmt != null) {
				try { stmt.close(); } catch (SQLException ex) { ex.printStackTrace(); }
			}
			if (conn != null) {
				try { conn.close(); } catch (SQLException ex) { ex.printStackTrace(); }
			}
		}
	}
}

Statement 객체

일반적인 SQL 문 사용 시

SQL 문을 실행할 때마다 컴파일 및 실행 과정을 반복

  • SQL문 compile -> compile된 SQL문 실행 -> 실행결과 반환

반복적인 작업 수행 시 DBMS의 부하 증가

PreparedStatement 객체

객체 생성 시 주어진 SQL 문을 미리 컴파일

  • 반복적인 컴파일을 피함으로써 DBMS 부하 감소 효과

SQL문 내에 매개변수(parameter) 사용 가능

매개변수를 제외하고 구조가 동일한 SQL 문을 반복 실행 시 효과적

CallableStatement 객체

Stored Procedure/Function 호출 시 이용

PreparedStatement 예시

String dml = "INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO)
				VALUES (?, ?, ?, ?)"; // DML 문 작성
                
Connection conn = DriverManager.getConnection(); // Connection 생성

// PreparedStatement 객체 생성
PreparedStatement pstmt = conn.prepareStatement(dml);

// parameter 값 설정: ? 자리에 들어갈 값을 지정
pstmt.setInt(1, empNo);
pstmt.setString(2, empName);
pstmt.setString(3, empJob);
pstmt.setInt(4, deptNo);

// DML 문 실행
int count = pstmt.executeUpdate(); // 주의: method 인자 없음!!

String query = “SELECT * FROM EMP 
				WHERE JOB = ? AND DEPTNO = ?”; // 질의문 작성
                
Connection conn = DriverManager.getConnection(); // Connection 생성

// PreparedStatement 생성
PreparedStatement pstmt = conn.prepareStatement(query); 

// parameter 값 지정
pstmt.setString(1, “CLERK”);
pstmt.setInt(2, 30);

// 질의문 실행
ResultSet rs = pstmt.executeQuery(); // 주의: method 인자 없음!!!

PStmtEx

public class PStmtEx {
	public static void main(String args[]) {
		Connection conn = null;
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		...
	try {
		conn = DriverManager.getConnection(url, user, passwd); // DBMS와의 연결 획득
		String query = "SELECT EMPNO, JOB FROM EMP WHERE ENAME=? ";
		
        // parameter가 포함된 질의문 작성
        pStmt = conn.prepareStatement(query); // PreparedStatement 객체 생성
        pStmt.setString(1, “SMITH”); // parameter 값 설정
        rs = pStmt.executeQuery(); // 질의 실행
        System.out.println("No JOB");
        while (rs.next()) { // DBMS 응답 처리
       		int no = rs.getInt("EMPNO");
			String job = rs.getString("JOB");
			System.out.println(no + " " + job);
		}
	} catch (SQLException ex) { ex.printStackTrace(); } 
	finally { … } // 자원 반납
} }