개인용 복습공간

[Jsp] JDBC로 데이터베이스 연동 - 3 (회원관리 만들기) 본문

웹/Jsp, Servlet

[Jsp] JDBC로 데이터베이스 연동 - 3 (회원관리 만들기)

taehwanis 2021. 5. 27. 22:50

 

 

 

PreparedStatement를 공부하고
회원관리 프로그램을 만들어보려고 한다.

 

 

 

 

 

 

PreparedStatement 사용하기

 

PreparedStatement

SQL의 틀을 미리 정해놓고, 나중에 값을 지정하는 방식으로 반복되는 질의문 수행에 효율적이다. 미리 컴파일된 SQL문을 사용하기 때문에 Statement에 비해 실행 속도가 빠르다.

PreparedStatement pstmt = conn.prepareStatement(SQL);

 

 - PreparedStatement 객체 생성

1
2
3
String sql = "insert into tblRegister (id, name) values(? , ?)";
 
PreparedStatement pstmt = conn.prepareStatement(sql);
cs

 

 - 질의문 실행

1
2
3
pstmt.setString(1, id);
pstmt.setString(2, name);
int success = pstmt.executeUpdate();
cs

 

executeQuery(SQL)는 DB의 구조와 테이블의 내용에 영향을 미치지 않는 질의에 적합하다.
select문에 쓰고 반환 값은 ResultSet객체이다.

executeUpdate(SQL)은 DB의 구조와 테이블의 내용에 영향을 미치는 질의에 적합하다.
create, drop, insert, delete, update문에 쓰고 반환 값은 create, drop은 0이고 insert, delete, update는
변경된 행의 수이다.

 

PreparedStatement를 사용한 회원관리 예제

회원관리 폴더 구조

 

다음은 delete, insert, modify, search 등 여러 메서드가 들어있는 MemberMgr.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
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
194
195
196
197
198
199
200
201
202
package mem;
 
import java.util.Vector;
import db.DBConnectionMgr;
import java.sql.*;
 
public class MemberMgr {
    
    private DBConnectionMgr pool = null;
    
    public MemberMgr() {
        try {
            pool = DBConnectionMgr.getInstance();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    
    public Vector<MemberBean> getMemberList(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Vector<MemberBean> vlist = new Vector<MemberBean>();
        
        try {
            conn = pool.getConnection();
            String sql = "select * from member";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while(rs.next()) {
                MemberBean bean = new MemberBean();
                bean.setId(rs.getString("id"));
                bean.setPwd(rs.getString("pwd"));
                bean.setName(rs.getString("name"));
                bean.setBirthday(rs.getString("birthday"));
                bean.setEmail(rs.getString("email"));
                
                vlist.addElement(bean);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt, rs);
        }
        
        return vlist;
    }
 
    
    public boolean insertMember(MemberBean bean    ) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        boolean success = false;
        
        try {
            conn = pool.getConnection();
            String sql = "insert into member values (?, ?, ?, ?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bean.getId());
            pstmt.setString(2, bean.getPwd());
            pstmt.setString(3, bean.getName());
            pstmt.setString(4, bean.getBirthday());
            pstmt.setString(5, bean.getEmail());
            
            int result = pstmt.executeUpdate();
            if(result > 0) {
                success = true;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt);
        }
        
        return success;
    }
    
    
    public MemberBean getMember(String id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        MemberBean bean = null;
        
        try {
            conn = pool.getConnection();
            String sql = "select * from member where id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();
            
            if(rs.next()) {
                bean = new MemberBean();
                bean.setId(rs.getString("id"));
                bean.setPwd(rs.getString("pwd"));
                bean.setName(rs.getString("name"));
                bean.setBirthday(rs.getString("birthday"));
                bean.setEmail(rs.getString("email"));
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt, rs);
        }
        
        return bean;
    }
    
    
    public boolean modifyMember(MemberBean bean) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        boolean success = false;
        
        try {
            conn = pool.getConnection();
            String sql = "update member set pwd=?, name=?, birthday=?, email=? where id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bean.getPwd());
            pstmt.setString(2, bean.getName());
            pstmt.setString(3, bean.getBirthday());
            pstmt.setString(4, bean.getEmail());
            pstmt.setString(5, bean.getId());
            
            int result = pstmt.executeUpdate();
            
            if(result > 0) {
                success = true;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt);
        }
        
        return success;
    }
    
    
    public boolean deleteMember(MemberBean bean) { //boolean타입의 메서드 매개변수는 MemberBean의 bean
        Connection conn = null;  //Connection 타입의 conn
        PreparedStatement pstmt = null//PreparedStatement 타입의 pstmt
 
        boolean success = false//리턴값을 위한 변변수 기본값 false
        
        try {
            conn = pool.getConnection(); //Connection객체를 얻어옴, DB와 연결
            String query = "delete from member where id = ?"//id로 delete하는 쿼리문
            pstmt = conn.prepareStatement(query); //conn 으로 sql문을 실행하고 결과를 pstmt에 받음
            pstmt.setString(1, bean.getId()); //id를 받아와 sql문 완성
            int result = pstmt.executeUpdate(); //result에 반환값을 받음, 변경된 행의 수
            
            if(result > 0//반환값이 0보다크면 리턴값을 true로, 1이므로 true
                success = true;
 
        }catch(Exception e) { //예외처리
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt); //사용된 객체들을 pool에 반환
        }
        
        return success;
    }
    
    
    public Vector<MemberBean> searchMemberList(String name){ //Vector<MemberBean> 메서드 매개변수는 String타입의 name
        Connection conn = null;    //Connection 타입의 conn
        PreparedStatement pstmt = null;    //PreparedStatement 타입의 pstmt
        ResultSet rs = null//ResultSet 객체를 받을 변수 rs
        Vector<MemberBean> vlist = new Vector<MemberBean>(); //컬렉션 생성 vlist
 
        try {
            conn = pool.getConnection(); //pool에서 Connection객체를 얻어옴
            String sql = "select * from member where name like ?"//이름으로 검색을 위한 like문
            pstmt = conn.prepareStatement(sql); //conn 으로 sql문을 실행하고 결과를 pstmt에 받음
            pstmt.setString(1,"%"+ name +"%"); //'%name%' 를 sql에 넣어줌
            rs = pstmt.executeQuery(); //ResultSet 객체에 쿼리결과값을 받음
            
            while(rs.next()) { //쿼리문으로 검색된 모든 결과를 vlist에 넣어줌
                MemberBean bean = new MemberBean(); //MemberBean 객체 생성
                bean.setId(rs.getString("id")); //id 지정
                bean.setPwd(rs.getString("pwd")); //pwd 지정
                bean.setName(rs.getString("name")); //name 지정
                bean.setBirthday(rs.getString("birthday")); //birthday지정
                bean.setEmail(rs.getString("email")); //email 지정
                
                vlist.addElement(bean); //vlist에 추가
            }
        }catch(Exception e) {
            e.printStackTrace();
        }finally {
            pool.freeConnection(conn, pstmt, rs); //사용된 Connection, PreparedStatement, ResultSet객체를 pool에 반환
        }
        
        return vlist; //vlist 반환
    }
 
//end class
 
cs

주석을 보고 참고하면 좋을 것 같다.

Comments