본문 바로가기

Program Language/Java

[JAVA] PreparedStatement DB insert, update, delete, select

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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package com.pstmt.score;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
 
import com.util.DBConn;
 
public class ScoreDAO {
    private Connection conn=DBConn.getConnection();
    
    // 테이블에 데이터 추가
    // insert into 테이블(컬럼) values(값)
    public int insertScore(ScoreDTO dto) {
        int result=0;
        String sql;
        PreparedStatement pstmt=null;
        
        try {
            sql="insert into score(hak,name,birth,kor,eng,mat)  values(?,?,?,?,?,?)";
            // PreparedStatement객체를 생성할 때 쿼리를 인자로 넘김
            pstmt=conn.prepareStatement(sql);
            
            // 데이터 설정
            pstmt.setString(1,dto.getHak());
            pstmt.setString(2,dto.getName());
            pstmt.setString(3,dto.getBirth());
            pstmt.setInt(4,dto.getKor());
            pstmt.setInt(5,dto.getEng());
            pstmt.setInt(6,dto.getMat());
            
            // 쿼리 실행(절대로 인수에 쿼리 대입하면 안됨)
            result=pstmt.executeUpdate();
            pstmt.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return result;
    }
    
    
    // 테이블 데이터 수정
    public int updateScore(ScoreDTO dto) {
        int result=0;        
        String sql;
        PreparedStatement pstmt=null;
        
        try {
            sql="update score set name=?,birth=?,kor=?,eng=?,mat=? where hak=?";
            
            // PreparedStatement객체를 생성할 때 쿼리를 인자로 넘김
            pstmt=conn.prepareStatement(sql);            
            // 데이터 설정            
            pstmt.setString(1,dto.getName());
            pstmt.setString(2,dto.getBirth());
            pstmt.setInt(3,dto.getKor());
            pstmt.setInt(4,dto.getEng());
            pstmt.setInt(5,dto.getMat());
            pstmt.setString(6,dto.getHak());
            // 쿼리 실행(절대로 인수에 쿼리 대입하면 안됨)
            result=pstmt.executeUpdate();
            pstmt.close();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        
        return result;        
    }
    
    // 테이블 데이터 삭제
    public int deleteScore(String hak) {
        int result=0;
        PreparedStatement pstmt=null;
        String sql;
        try {
            sql="DELETE FROM score WHERE hak=?";
        
            pstmt=conn.prepareStatement(sql);
            result=pstmt.executeUpdate();
            pstmt.close();
            pstmt=null;
            
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
        return result;
    }
 
    // 전체 및 검색
    // 전체가 다 나오는 검색, 이름 검색
    // searchKey : 검색할 컬럼명   
    public List<ScoreDTO> listScore(
             String searchKey, String searchValue) {
        ArrayList<ScoreDTO> list=new ArrayList<ScoreDTO>();
        StringBuffer sb=new StringBuffer();
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        
        try {
            
            // 검색이 아닌 경우
            if(searchValue==null||searchValue.length()==0){
                sb.append("select hak,name,to_char(birth,'yyyy-mm-dd') birth,");
                sb.append("kor,eng,mat, (kor+eng+mat) tot,");
                sb.append("(kor+eng+mat)/3 ave, rank() over(order by (kor+eng+mat) desc) rank");
                sb.append(" from score ");            
                
                pstmt=conn.prepareStatement(sb.toString());
                //?가 없으므로 setter가 없음
                rs=pstmt.executeQuery(); //executeQuery:resultSet의 객체를 리턴
                  
                                
            }else// 검색인 경우
                sb.append("select * from (");
                sb.append("  select hak,name,to_char(birth,'yyyy-mm-dd') birth,");
                sb.append("kor,eng,mat, (kor+eng+mat) tot,");
                sb.append("(kor+eng+mat)/3 ave, rank() over(order by (kor+eng+mat) desc) rank");
                sb.append(" from score ");    
                sb.append(") where "+searchKey+" LIKE ?||'%' ");
                
                pstmt=conn.prepareStatement(sb.toString());
                pstmt.setString(1, searchValue);
                rs=pstmt.executeQuery();
            }        
            
            while(rs.next()){  // bof- eof
                ScoreDTO dto=new ScoreDTO();
                dto.setHak(rs.getString("hak"));
                // 또는 dto.setHak(rs.getString(1));
                dto.setName(rs.getString("name"));
                dto.setBirth(rs.getString("birth"));
                dto.setKor(rs.getInt("kor"));
                dto.setEng(rs.getInt("eng"));
                dto.setMat(rs.getInt("mat"));
                dto.setTot(rs.getInt("tot"));
                dto.setAve(rs.getInt("ave"));
                dto.setRank(rs.getInt("rank"));
                
                list.add(dto);
            }
            rs.close();
            pstmt.close();
            pstmt=null;    
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return list;
    }
 
    // 학번검색
    public ScoreDTO readScore(String hak) {
        ScoreDTO dto=null;
        StringBuffer sb = new StringBuffer();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            sb.append("select hak,name,");
            sb.append(" to_char(birth,'yyyy-mm-dd') birth,");
            sb.append(" kor,eng,mat,(kor+eng+mat) tot,");
            sb.append(" (kor+eng+mat)/3 ave");
            sb.append(" from score");
            sb.append(" where hak =?");
            pstmt=conn.prepareStatement(sb.toString());
            pstmt.setString(1, hak);
            rs=pstmt.executeQuery();
            
            if(rs.next()){
                dto=new ScoreDTO();
                dto.setHak(rs.getString("hak"));
                dto.setName(rs.getString("name"));
                dto.setBirth(rs.getString("birth"));
                dto.setKor(rs.getInt("kor"));
                dto.setEng(rs.getInt("eng"));
                dto.setMat(rs.getInt("mat"));
                dto.setTot(rs.getInt("tot"));
                dto.setAve(rs.getInt("ave"));                
            }
            rs.close();
            pstmt.close();
            pstmt=null;
 
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return dto;        
    }
}
 

 

'Program Language > Java' 카테고리의 다른 글

JAVA JDBC DB연결 (중요도3)  (0) 2014.11.24
문자(열) 입력 방법  (0) 2014.11.04
컬렉션(Collection)_Map  (0) 2014.11.04
컬렉션(Collection)_Set  (0) 2014.11.04
컬렉션(Collection)_List  (0) 2014.11.04