minlog
article thumbnail

 

JDBC 인터페이스 

프로그래머에게 쉬운 데이터베이스와 연동되는 프로그램을 작성할 수 있게하는 도구

 

💡 JDBC API (java.spl 패키지)

API 설명
Driver  모든 드라이버 클래스들이 구현해야 하는 인터페이스
DriverManager 드라이버를 로드하고 데이터베이스에 연결
Connection 특정 데이터베이스와의 연결
Statement  SQL문을 실행해 작성된 결과를 반환
PreparedStatement 
사전에 컴파일된 SQL문을 실행 
쿼리문에 넣을 값이 가능한지 확인 시켜주는 기능으로 sql injection 예외를 방지한다. (해킹 방지)
ResultSet  SQL문에 대한 결과를 얻어냄

 

 

💡 JDBC 프로그래밍 단계

 

1. VO 클래스 생성

받아야하는 객체를 만들어줄 클래스를 생성한다.

 

2. Dao 클래스 생성

실제 데이터배이스에 접근해서 데이터를 가져오거나 데이터를 넣는 역할을 하는 데이터 객체

 

1) JDBC드라이버 인스턴스 생성 

동적로딩으로 (실행시점에서 객체를 생성하는 방법)

Class.forName("oracle.jdbc.driver.OracleDriver");

 

2) JDBC 드라이버 인스턴스를 통해 DBMS에 대한 연결 생성

String DBurl = "jdbc:oracle:thin:@localhost:1521:xe"

Connection conn = DriverManager.getConnection( DBurl, " 아이디 ", " 비밀번호 ");

 

3) 쿼리문 작성

String query = "INSERT INTO AUTHOR VALUES (seq_author_id.nextval, ?, ? )";

PreparedStatement pstat = conn.prepareStatement(query);

 

4 - 1) 질의문 실행  :

추가 insert / 수정 update / 삭제 delete  -  executeUpdate( )

pstat.executeUpdate(); // 결과값 저장 ( 정수 값 반환됨  0 또는 양수)

 

4 - 2) 질의문 실행 :

리스트 출력 select  -  executeQuery( ) 

ResultSet rs =  pstat.executQuery();  // 반환 (정수 값 반환 -1 또는 양수)

 

5) ResultSet 해지

rs.close();

 

6) Statement 해지

ps.close(); 또는 stmt.close();

 

7) 데이터베이스 연결 해지

conn.close();

 

 

 

 

 

🍫 실제 연결 예시

 

1. JDBC드라이버  연결 ( getConnection 메소드 )

public Connection getConnection() throws SQLException{
    //데이터베이스 접속 oracle 기준
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String user = "아이디";
    String password = "비밀번호";
    Connection conn = null;
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      conn = DriverManager.getConnection(url, user , password);
    } catch (ClassNotFoundException e) {
      System.err.println("JDBC 드라이버 로드 실패!");
    }
    return conn;

}

 

2. 데이터베이스 추가 기능 구현 ( insert )

int 값을 리턴한다.  ( ex . 리턴된 int 는 if문으로 객체를 화면에 나타내줄때 사용. )

setString 메소드 - 전달 받은 쿼리문에서 물음표(?)부분에 들어갈 내용을 전달. - setString( ?번째 , 내용값 )

--> 수정. 삭제 기능도 쿼리문을 제외 동일 하다.

public int insert(AuthorVo vo) {
    int count = -1;
    try {
      Connection conn = getConnection();
      String query = "INSERT INTO AUTHOR VALUES (seq_author_id.nextval, ?, ? )";
      PreparedStatement pstat = conn.prepareStatement(query);
      
      pstat.setString(1, vo.getAuthor_name());
      pstat.setString(2, vo.getAuthor_desc());
      
      count = ps.executeUpdate();
      
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
      	//완료되면 JDBC 제거하기
        pstmt.close();
        conn.close();
      } catch (SQLException e) {
        System.out.println("error:" + e);
      }
    }
    System.out.println("추가 성공");
    return count;
  }

 

 

2. 데이터베이스 리스트 기능 구현 ( getList )

리스트배열을 리턴한다.  ( ex . 리턴된 리스트는 for문으로 전체 리스트 객체를 화면에 나타내줄때 사용. )

re.next() -  ResultSet 에서 전달 받은 값이 있으면 true 없으면 faluse  , while문을 값이 없을때까지 리트스 값을 받아낸다.

 public List<AuthorVo> getList() {
	ArrayList<AuthorVo> arraylist= new ArrayList<AuthorVo>(); // 불러온 객체 넣어줄 배열
	
	try {
		Connection conn = getConnection();
		String query = "SELECT * FROM AUTHOR";
	    PreparedStatement ps = conn.prepareStatement(query);
		ResultSet rs = ps.executeQuery();
		
		while (rs.next()) {
			AuthorVo vo = new AuthorVo(rs.getInt("AUTHOR_ID"), rs.getString("AUTHOR_NAME"), rs.getString("AUTHOR_DESC"));
			arraylist.add(vo);
		}
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
      try {
      	//완료되면 JDBC 제거하기
        pstmt.close();
        conn.close();
        rs.close();
      } catch (SQLException e) {
        System.out.println("error:" + e);
      }
    }
	
	System.out.println("조회성공");
	
    return arraylist;
  }
profile

minlog

@jimin-log

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!