2019.02.07 JAVA로 DB연동하기

2019. 2. 7. 15:50JAVA


#1 DB연결 : bulid path 작업


① lib(임의)폴더를 생성한다.


② ojdbc6.jar을 복사해서 붙여넣는다.

->> C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib에 존재


③ Build Path로 연결한다.


④ Add JARs 혹은 Add External JARs로 ojdbc6.jar을 추가한다.


->Add JARs를 사용할 경우 팝업창




⑤ 적용이 완료된다면 다음과 같은 파일구성을 확인할 수 있다.



#2 생성자와 getter&setter를 

    포함된 필드를 생성한다=> Location.java

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
package com.example;
 
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
 
public class Location {
    static List<String> list = new ArrayList<String>();
    private String City;
    private double ww;
    private double jj;
    private Timestamp reg_date;//등록날짜
    
    public Location(String City,double ww, double jj){
        super();
        this.City= City;
        this.ww = ww;
        this.jj = jj;
        this.reg_date= reg_date;
        
    }
    public Location() {
        super();
    }
    
 
    public Timestamp getReg_date() {
        return reg_date;
    }
 
 
    public void setReg_date(Timestamp reg_date) {
        this.reg_date = reg_date;
    }
 
 
    public String getCity() {
        return City;
    }
 
    public void setCity(String city) {
        City = city;
    }
 
    public double getWw() {
        return ww;
    }
 
    public void setWw(double ww) {
        this.ww = ww;
    }
 
    public double getJj() {
        return jj;
    }
 
    public void setJj(double jj) {
        this.jj = jj;
    }
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(City).append("\t").append(ww).append("\t").append(jj)
        .append("\t").append(reg_date);
        return builder.toString();
    }
    
}
 
cs


#3 locationDao.java => SQL문&기능 메소드 

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.example;
//Data Access Object : DAO, 데이터 접근 객체 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
 
public class locationDao {
    // DB연결
    private Connection getConnection() throws Exception {
        String url = "jdbc:oracle:thin:@localhost:1521:xe";
        String user = "scott";
        String passwd = "tiger";
        Connection con = null;
 
        Class.forName("oracle.jdbc.OracleDriver");
        con = DriverManager.getConnection(url, user, passwd);
        return con;
    }
 
    // JDBC 자원 닫기 메소드
    private void closeJDBC(Connection con, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
 
    public int insert(Location location) {
        int rowCount = 0;
        Connection con = null;
        PreparedStatement pstmt = null;
        String sql = "";
 
        // 현재 시스템의 날짜 가져오기
        Timestamp reg_date = new Timestamp(System.currentTimeMillis()); // 현재 시스템의 날짜
 
        try {
            con = this.getConnection();
            sql = "INSERT INTO location(city_name,longitude,latitude,reg_date) " + " VALUES(?,?,?,?)";
            pstmt = con.prepareStatement(sql); // sql문 전달
            pstmt.setString(1, location.getCity());
            pstmt.setDouble(2, location.getJj());
            pstmt.setDouble(3, location.getWw());
            pstmt.setTimestamp(4, reg_date);
 
            // 데이터를 DB에 갱신
            rowCount = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // JDBC 자원 닫기
            closeJDBC(con, pstmt, null);
        }
        return rowCount;
    } // insert()
    
    
    
 
    public List<Location> selectAll(){
        List<Location> list = new ArrayList<Location>();
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "";
        
        try {
            con = getConnection();
            sql= "SELECT * FROM location ORDER BY city_name ASC"// 도시이름의 오름차순
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while(rs.next()) {
                Location  loc = new Location();
                loc.setCity(rs.getString("city_Name"));
                loc.setJj(rs.getDouble("longitude"));
                loc.setWw(rs.getDouble("latitude"));
                loc.setReg_date(rs.getTimestamp("reg_date"));
                  
                list.add(loc);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeJDBC(con, pstmt, rs);
        }
        return list;
    }//selectAll()
    
    
    public Location selectByCityName(String cityName) {
        Location loc = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "";
        
        try {
            con = getConnection();
            sql = "SELECT * FROM location WHERE city_Name=?    "// ? 는 아직 미완성된 부분
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, cityName); // ?을 채워주는 작업
            
            rs = pstmt.executeQuery();
            if(rs.next()) {
                loc = new Location();
                loc.setCity(rs.getString("city_Name"));
                loc.setJj(rs.getDouble("longitude"));
                loc.setWw(rs.getDouble("latitude"));
                loc.setReg_date(rs.getTimestamp("reg_date"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeJDBC(con, pstmt, rs);
        }
        
        return loc;
    }// selectByCityName()
    
}
 
cs



#4 DBLocationManager.java 

=> 화면표시 및 메소드 호출을 담당하는 클래스

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.example;
 
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class DBLocaionManager {
    private locationDao locationDao = new locationDao();
    private Scanner sc = new Scanner(System.in);
 
    public Scanner getSc() {
        return sc;
    }
 
    public void setSc(Scanner sc) {
        this.sc = sc;
    }
 
    public void save() {
        System.out.println("도시,경도,위도 입력");
        System.out.print(">>");
        String strInput = sc.nextLine(); // 사용자 입력값
 
        StringTokenizer st = new StringTokenizer(strInput, ","); // 입력값을 ","를 기준으로 토큰화
        String[] tokens = new String[3]; // 토큰을 담을 객체
        int count = 0// 토큰 추출 작업에 필요한 int변수 선언( while을 위한 제어변수)
 
        // 토큰 추출 작업
        while (st.hasMoreTokens()) {
            tokens[count++= st.nextToken().trim(); // trim은 양끝단의 공백을 제거
        }
        double longitude = Double.parseDouble(tokens[1]); // wrapper 작업
        double latitude = Double.parseDouble(tokens[2]);
 
        Location location = new Location(tokens[0], longitude, latitude); // location 클래스에 주입
        // Dao의 insert 메소드 호출로 대체
        locationDao.insert(location);
 
    }// save()
 
    public void listAll() {
        System.out.println("--------------------------");
        System.out.println("Table에 있는 모든 도시 출력");
        List<Location> list =locationDao.selectAll();
        for(Location loc : list) {
            System.out.println(loc);
        }
        System.out.println("--------------------------");
        
 
    }// listAll()
 
    public void cityInfo() {
        System.out.println("==============");
        System.out.println("도시 이름으로 검색하기");
        System.out.println("도시이름 >>");
        
        String cityName = sc.nextLine().trim();
        
        Location loc = locationDao.selectByCityName(cityName);
        if(loc==null) {
            System.out.println(cityName+"은 없습니다.");
            return;
        }
        System.out.println(loc);
        System.out.println("");
    }// cityInfo()
 
    public static void main(String[] args) {
        DBLocaionManager manager = new DBLocaionManager();
        Scanner scan = manager.getSc();
 
        while (true) {
            System.out.println("메뉴 선택:  1.입력 , 2.전체목록 , 3.검색, 4.종료");
            System.out.println(">>");
            String menu = scan.nextLine();
 
            if (menu.equals("1")){
                manager.save();
            } else if (menu.equals("2")) {
                manager.listAll();
            } else if (menu.equals("3")) {
                manager.cityInfo();
            } else if (menu.equals("4")) {
                break;
            }
        } // while
 
        System.out.println("프로그램 종료");
 
    }
 
}
 
cs




#5 출력