가자공부하러!

2. Oracle DB - java 연동 예제(eclipse) 본문

공부/DB

2. Oracle DB - java 연동 예제(eclipse)

오피스엑소더스 2019. 5. 31. 20:30

https://github.com/HyeongJunMin/StudyJava/tree/master/4_JDBC/src


1. 클래스

  > JDBCMain.java : 메인메소드


  > DBConnection.java : DB연동기능

- public static boolean setDBByStudentList(List stdLst) : 

ㄴ Student객체들이 저장된 List를 매개변수로 받음

ㄴ 각 Student 객체의 학번을 DB 내 학생 테이블에서 검색

ㄴ 학번이 있으면 UPDATE

ㄴ 학번이 없으면 INSERT


  > Student.java : Student 객체 DTO

- 필드 : 

ㄴ int : 학번

ㄴ String : 이름, 입학일시, 전공, 단과대학

ㄴ static int : 총 생성된 Student 객체 수(누적)


  > StudentDAO.java : Student DAO

  

















1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.sql.*;
 
public class DBConnectionTest {
    public static void main(String[] args) {
        connectionDB();
        
 
    }
    public static void connectionDB() {
        Connection con = null;
        
        String user = "minhj";
        String pw = "1234";
        String url = "jdbc:oracle:thin:@localhost:1521:studyDB";
        String sql;
        sql ="INSERT INTO 학생 (학번) VALUES(1002)";
        //이름 입학일시 전공 단과대학
        String upd = "UPDATE 학생 SET 이름='만득', 입학일시='2009/03/02', 전공='컴퓨터공학', 단과대학='공대' WHERE 학번=1002";
        
        
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(url, user, pw);
            System.out.println("DB연결 성공!");
            Statement stmt = con.createStatement();
            stmt.executeQuery(upd);
            System.out.println("업데이트 성공!");
            
            doSelectQuery(stmt);
            
            stmt.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("실패");
        } finally {
            try {
                if( con != null)
                    con.close();
            }catch(Exception e) {
                
            }
        }
    }
    
    public static void doSelectQuery(Statement s) {
        String slt = "SELECT * FROM 학생";
        ResultSet rs;
        try {
            rs = s.executeQuery(slt);
            
            while( rs.next() ) {
                int num = rs.getInt("학번");
                String name = rs.getString("이름");
                String time = rs.getString("입학일시");
                String major = rs.getString("전공");
                String clg = rs.getString("단과대학");
                System.out.println(num + "\t" + name + "\t" + time + "\t" + major + "\t" + clg);
                //전공, 단과대학
            }
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
 
    }
}
 
cs


db연결 결과


db상태

































Comments