세로형
Recent Posts
Recent Comments
Link
03-29 03:47
«   2024/03   »
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
Archives
Today
Total
관리 메뉴

꿈 많은 사람의 이야기

자바 mysql 연동(JDBC 이용), preparedstatment 본문

java

자바 mysql 연동(JDBC 이용), preparedstatment

이수진의 블로그 2017. 8. 18. 08:44

db의 값을 출력하고 업데이트 등의 과정을 하면서 쿼리문이 좀 복잡해질 수도 있다.

예를들어 insert into saram(id, name, age) values('"+id+"', '"+name+"', '"+age+"');
이런식으로 해야하는데 큰 따옴표, 작은 따옴표가 헷갈리기도 하고 복잡해 보인다. 이런 것을 방지하고 좀 간단하게 쿼리를 처리해주는 기능이
PreparedStatement이다.

동작 하는 방법은 이런식이다.

1
2
3
4
5
6
String sql = "insert into saram(id, name, age) values(?,?,?)"
PreparedStatement pstmt = conn.prepareStatement(sql); 
 
pstmt.setString(1, id); 
pstmt.setString(2, name); 
pstmt.setInt(3, age);
Colored by Color Scripter



sql문을 문자열로 만들고 PreparedStatement 클래스 객체를 만든다. 그 객체는 connection 객체에 있는 prepareStatement() 메소드로 받게 된다. 이때 sql을 먼저 넣는데 과거 그냥 Statment와는 다르다.

일반적인 statment는 다음과 같다.

1
2
stmt = conn.createStatement(); 
rs = stmt.executeQuery(sql);

즉 문장를 셋팅해줄때 -> createStatement()메소드에 sql을 넣지 않는다.
쿼리를 실행할 때 sql을 넣어준다. 하지만 preparedStatement는 다르다.

1
2
3
4
5
6
7
PreparedStatement pstmt = conn.prepareStatement(sql);
        
pstmt.setString(1, id);  //id등은 그냥 자바 변수
pstmt.setString(2, name);
pstmt.setInt(3, age);
        
int res = pstmt.executeUpdate();

PreparedStatement는 바로 connection 객체로 생성할 때 sql을 보낸다. 그리고 나서 ? 값들을 셋팅해준다.
pstmt.setString(1, id)는 첫번째 ? 에 id 변수를 셋팅(그냥 평범한 자바 변수이다)
pstmt.setString(2, name) 은 두 번째 ? 에 name(평범한 자바 변수) 셋팅

이런식으로 셋팅하고 나서
pstmt.executeUpdate() -> insert, update, delete -> int 반환
pstmt.executeQuery() -> select   ->  ResultSet 반환
을 진행한다.

이 PreparedStatement를 하게 되면 간결하고 혼란없이 쿼리 요소를 구성할 수 있다.

다음은 본인이 만든 MySQL과 연동된 자바 소스이다.
select, insert, update, delete, search 기능이 메소드 별로 나뉘어져 있다.

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
 
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
 
public class TestJDBC3 {
    
    public static Scanner in = new Scanner(System.in);
 
    public static Connection getConnection() throws ClassNotFoundException, SQLException  {
        
        String url = "jdbc:mysql://localhost:3306/test";
        String user = "root";
        String pwd = "apmsetup";
        Connection conn = null;
        
        Class.forName("org.gjt.mm.mysql.Driver");
        conn = DriverManager.getConnection(url, user, pwd);
        System.out.println("접속");
            
        
        return conn;
    }
    //SELECT 처리용
    public static void selectAll() throws ClassNotFoundException, SQLException
    {
        
        Connection conn = getConnection();
        String sql = "SELECT * FROM saram";
        ResultSet rs = null;
        Statement stmt = null;
        
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        
        while(rs.next())
        {
            String id = rs.getString(1);
            String name = rs.getString(2);
            int age = rs.getInt(3);
            
            System.out.println(id + ", "+name+", "+age);
        }
        
        if(rs != null) rs.close();
        if(stmt != null) stmt.close();
        if(conn != null) conn.close();
    }
    
    public static void insert(String id, String name, int age) throws ClassNotFoundException, SQLException
    {
        //입력하는 메소드
        Connection conn = getConnection();
        String sql = "insert into saram(id, name, age) values(?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        
        pstmt.setString(1, id);
        pstmt.setString(2, name);
        pstmt.setInt(3, age);
        
        int res = pstmt.executeUpdate();
        if(res > 0)
        {
            System.out.println("처리 완료");
        }
        
        if(pstmt != null) pstmt.close();
        if(conn != null) conn.close();
    }
    
    public static void update(String id, String name) throws ClassNotFoundException, SQLException
    {
        //수정 기능
        Connection conn = getConnection();
        
        String sql = "update saram set name = ? where id = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, name);
        pstmt.setString(2, id);
        
        int res = pstmt.executeUpdate();
        if(res > 0)
        {
            System.out.println("업데이트 완료");
            selectAll();
        }
        else
            System.out.println("값이 없습니다.");
    }
    
    public static void delete(String id) throws ClassNotFoundException, SQLException
    {
        //삭제기능
        
        Connection conn = getConnection();
        
        String sql = "delete from saram where id =?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, id);
        int res = pstmt.executeUpdate();
        if(res > 0)
        {
            System.out.println("삭제되었습니다.");
            selectAll();
        }
        else
            System.out.println("값이 없습니다.");
    }
    
    public static void search(String id) throws ClassNotFoundException, SQLException
    {
        //검색기능
        Connection con = getConnection();
        String sql = "select * from saram where id = ?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, id);
        int res = pstmt.executeUpdate();
        if(res > 0)
        {
            
        }
    }
    
    public static void main(String args[]) throws ClassNotFoundException, SQLException
    {
        //insert("TestId","TestName",20);
        //selectAll();
        
        System.out.println("사람 정보 관리 프로그램");
        String[] menuItems = {"input","output","search","modify","delete","end"};
        for(int i = 0 ; i < menuItems.length ; i++)
        {
            System.out.print(i+1+". "+menuItems[i] +" ");
        }
        System.out.println();
        
        int no = 0;
        do{
            System.out.println("choice : ");
            no = in.nextInt();
        }
        while(no < 1 || no > menuItems.length);
        //의존성을 낮게 한다. menuItems랑 별개의 기능으로 되니까.
        //메뉴의 변경에 따라 얘도 자동적으로 변경되고 .. 이런식의 로직을 짜고 이런것은 왠만하면 메소드로 빼버린다.
        //이렇게 안하고 단순하게 하려면 내가 처음에 했던 그냥 메뉴만 System~으로 출력하게 하는거
        String id = null;
        String name =null;
        int age = 0;
        
        switch(no)
        {
        case 1:
            id = in.next();
            name = in.next();
            age = in.nextInt();
            insert(id,name,age);
            break;
        case 2:
            selectAll(); 
            break;
        case 3:
            System.out.println("검색할 아이디를 입력하세요");
            id = in.next();
            search(id);
            
            break;
        case 4:
            System.out.println("업데이트 시킬 아이디와 변경할 이름을 입력하세요");
            id = in.next();
            name = in.next();
            update(id, name); 
            System.out.println("업데이트");
            break;
        case 5:
            System.out.println("삭제할 아이디 입력");
            id = in.next();  //
            delete(id);
            
            break;
        case 6
            System.out.println("종료합니다.");
            System.exit(0);
        }
        
        main(new String[]{""});  //재귀호출
        
        
    }
 
}
 
Colored by Color Scripter

설명상 재귀호출로 메인을 계속 호출했는데 이것보단 while(true)로 계속 호출하는게 더 좋다.

여기까지가 기본적인 JDBC연동이다.


반응형
그리드형
Comments