프로그래밍/Database

PreparedStatement의 사용법

Jay Tech 2017. 1. 19. 11:58
반응형

PreparedStatement는 Statement와 동일한 기능을 하지만 차이점이 있다면 전자는 미리 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
<%
    request.setCharacterEncoding("euc-kr");
    
    String memberID = request.getParameter("memberID");
    String password= request.getParameter("password");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    
    Class.forName("com.mysql.jdbc.Driver");
    
    Connection conn = null;
    PreparedStatement pstmt = null;
 
    try {
        String jdbcDriver = "jdbc:mysql://localhost:3306/test?" +
                            "useUnicode=true&characterEncoding=euckr";
        String dbUser = "user";
        String dbPass = "password";
        
        conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
        pstmt = conn.prepareStatement(
            "insert into MEMBER values (?, ?, ?, ?)");
        pstmt.setString(1, memberID);
        pstmt.setString(2, password);
        pstmt.setString(3, name);
        pstmt.setString(4, email);
        
        pstmt.executeUpdate();
    } finally {
        if (pstmt != nulltry { pstmt.close(); } catch(SQLException ex) {}
        if (conn != nulltry { conn.close(); } catch(SQLException ex) {}
    }
 
%>
cs



line 21 - 실행할 쿼리를 미리 입력하는데 값이 들어가는 부분은 ?로 대치한 쿼리를 사용한다.


line 23 - setString은 첫번째 인자로 물음표의 위치가 들어가고 두번째로는 값이 들어간다.



PreparedStatement를 생성할 때에 실행할 쿼리를 지정하기 때문에 이들 두 메서드는 쿼리를 인자로 전달받지 않는다.


ResultSet executeQuery() - SELECT 쿼리를 실행할 때 사용되며 ResultSet을 결과값으로 리턴한다.


int executeUpdate() - INSERT, UPDATE, DELETE 쿼리를 실행할 때 사용되며, 실행결과 변경된 레코드의 개수를 리턴한다.




반응형