본문 바로가기

카테고리 없음

jdbc를 사용해 select하는 예제 - mysql가 DB인 경우

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
public class RoleDao {
    //timezone오류 발생시 뒤에 serverTime을 명시해 주자
private static String dburl = "jdbc:mysql://localhost:3306/connectdb?serverTimezone=UTC";
    private static String dbUser = "connectuser";
    private static String dbpasswd = "connect123!@#";
    
    public Role getRole(int roleId) {
        Role role = null;
        Connection conn = null;
        PreparedStatement ps =null;
        ResultSet rs =null;
        try {
//8.0버전 이상에서 작동하는 클래스 이름
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(dburl,dbUser,dbpasswd);
            String sql = "SELECT role_id, description FROM role WHERE role_id =?"
            ps = conn.prepareStatement(sql);
           // ? 에 바인딩 하기 위한 setInt 메소드
ps.setInt(1,roleId);
            rs = ps.executeQuery();
            if(rs.next()) {
                int id = rs.getInt(1); //파라미터로 인덱스 입력(role_id의 인덱스 1) 혹은
                String description = rs.getString("description");//칼럼명 입력하면 됨
                role = new Role(roleId, description);
            }
        } catch (Exception e) {
         e.printStackTrace();
        }finally {
//만약 결과가 없다면 nullPointException 발생. 그 가능성 배제
            if(rs!=null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(ps!=null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
        
        return role;
    };
    
}
cs