웹개발/jsp

[JSP] #7 JDBC-2 JSP 에서 DB 사용방법

RBWSN 2015. 3. 24. 03:31
728x90
JSP에서 Db를 사용하려면 JDBC를 사용해 데이터 베이스와 연동해야하한다.

먼저 단계를 살펴보자

먼저 1단계는 JDBC 드라이드버를 로드하여 구현하는 작업이다.
Class의 forName 메서드를 사용하여 드라이버를 로드한다.
Class.forName(Driver)


이렇게 사용이 가능하다.

2단꼐로는 Connection 객체를 생성한다.

Database Connections 의 드라이버를 Connection 객체로 생성하여 받는다.
Connection connection = DriverManager.getConnection( )

이런식으로 사용한다 만약에 드라이버를 찾지못하면 에러가 난다.

3단계로는 sql쿼리를 생성한다.
반환될 결과값을 가져오게 할 작업 영역을 제공한다.
Statement statement= connection.createStatement();

이렇게 사용이 가능하다.

4단계는 작업영역을 가지고 쿼리를 수행한다.
ResultSet set = statement.executeQuery(select문);

String sql= "update Insert Delete 문에서 사용 sql코드 입력후" ;
statement.executeUpdate(sql);

두가지 방법이 있다.

5단계는 이제 select 결과물인 exectueQuery문에서 수행한 결과인 ResultSet으로 부터 원하는 데이터를 추출한다.
한행씩이동하면 get 메서드를 이용하여 원하는 결과물을 찾는다.
while(set.next()){
       out.print(set.getString( "name"));
       out.print(set.getString( "id"));
}

이런식으로 하나씩 찾는다.


예외처리도 중요하다.

 클래스가 없거나 sql 언어가 오류가나면 예외가 발생하므로 예외처리를 해주어야한다.를 보자 JDBC 드라이버를 사용하여 커넥션을 만드는 역할을 하는데 이메소드는 만약 드라이버 클래스가 없으면 예외를 발생시키므로 예외처리를 해야한다.

기본적으로 JDBC가 연결되는지 실험해보자.




url부터 드라이버 매니져에 들어가면된다 .


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
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>드라이버 연결테스트</title>
</head>
<body>
<h2>드라이버 테스트</h2>
<%
try{
    String Url = "jdbc:mysql://localhost:3306/dbroot";
    String id = "dbuser";
    String passwd = "dbpass";
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(Url,id,passwd);
    out.print("제대로연결완료");
}catch(Exception e){
    e.getStackTrace();
}
 
 
%>
 
</body>
</html>
cs

이렇게 코드를 사용하여 

제대로 연결이 되었다면 jDBC가 연결이 된것이다.

저문구가 뜨지않는다면 다시한번 살펴 봐야한다.


이제는 JSP페이지 내에서 테이블에 레코드를 추가 해보겠다.






성공적으로 데이터가 테이블에 저장된 모습을 볼 수 있다.

코드를 보도록하자.

07-2.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>데이터 입력폼</title>
</head>
<body>
<h2>데이터 입력폼</h2>
 
<form action="07-2-1.jsp" method="post">
 
이름 : <input type="text" name="name"><br>
아이디 : <input type="text" name="id"><br>
패스워드 : <input type="text" name="passwd"><br>
<input type="submit" value="완료"
 
</form>
 
 
</body>
</html>
cs


07-2-1.jsp

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
<%@page import="java.sql.Timestamp"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%request.setCharacterEncoding("utf-8");%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>레코드 추가폼</title>
</head>
<body>
<%!
String str;
%>
 
<%
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
String name = request.getParameter("name");
Timestamp timestamp = new Timestamp(System.currentTimeMillis()); // 현재 시각을 얻어옴
 
try{
    String Url = "jdbc:mysql://localhost:3306/dbroot"
    String userid = "dbuser";
    String userpasswd = "dbpass";
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(Url,userid,userpasswd);
    
    String sql = "insert into member values(?,?,?,?)"// sql 멤버 값으로 4개의 공간을 확보
    
    PreparedStatement statement= connection.prepareStatement(sql); //먼저 스테이트 생성
    statement.setString(1, id); // 1번째 필드에 id
    statement.setString(2, passwd); // 2번째 passwd
    statement.setString(3, name); // 3번째 name
    statement.setTimestamp(4, timestamp); // 4번째 현재시각
    statement.executeUpdate(); // sql을 실행
    
    if(statement!=null){ // 스테이트먼트 해제
        statement.close();
    }
    if(connection !=null){ //커넥션해제
        connection.close();
    }
    str = "레코드 추가 완료"// 완료가 끝까지 되었다면 str에 문자열 넣기
 
}catch(Exception e){
    e.getStackTrace();
}
 
%>
<%=str%>
 
 
 
</body>
</html>
cs

레코드가 성공적으로 추가된 것을 볼 수 있다.

이번에는 레코드들은 가져오도록 해보자 


먼저 결과창이다. 레코드를 가져온것을 확인할 수 있다.

코드를 보자.

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>레코드 가져오기</title>
</head>
<body>
<h2>레코드 가져오기</h2>
<%! // 전역변수로 설정
String id;
String passwd;
String name;
Timestamp timestamp;
 
%>
 
<%
try{
    
    String Url = "jdbc:mysql://localhost:3306/dbroot"
    String userid = "dbuser";
    String userpasswd = "dbpass";
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(Url,userid,userpasswd);
    
    String sql = "select * from member";
    PreparedStatement statement = connection.prepareStatement(sql); // 모든 데이터들을 가져온다는 인터페이스와 연결
    ResultSet set= statement.executeQuery(); // 쿼리 실행
    
    while(set.next()){
        id = set.getString("id");
        passwd = set.getString("passwd");
        name = set.getString("name");
        timestamp = set.getTimestamp("reg_date");
        
       %>
        <%-- 출력문  --%>
        아이디 : <%=id%><br>
        패스워드 : <%=passwd%><br>
        이름 : <%=name%><br>
        날짜 : <%=timestamp.toString()%><br>
        <hr>
        <%-- 출력문 닫기 --%>
        <% 
        
        
    }
    if(set!=null){ // 객체들 닫기
        set.close();
    }
    if(statement !=null){
        statement.close();
    }
    if(connection !=null){ 
        connection.close();
    }
    
}catch(Exception e){
    e.getStackTrace();
}
%>
 
 
 
</body>
</html>
cs

코드는 이런식으로 나타내었다.

이번에는 레코드를 수정해보도록 하자.

]


결과화면이다 변경이완료되면 저렇게 테이블 명이 바뀌게된다.

코드를 보자
07-4.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>수정폼</title>
</head>
<body>
<h2>레코드 수정 폼</h2>
 
<form action="07-4-1.jsp" method="post">
아이디 : <input type="text" name="id"><br>
패스워드 : <input type="text" name="passwd"><br>
이름 변경 : <input type="text" name="name"><br>
<input type="submit" value="완료">
</form>
 
 
</body>
</html>
cs

07-4.1.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.sql.*"%>
    <%request.setCharacterEncoding("utf-8");%>
    <%!
String str;
%>
 
<%
try{
    String id = request.getParameter("id");
    String passwd = request.getParameter("passwd");
    String name = request.getParameter("name");
    
    String Url = "jdbc:mysql://localhost:3306/dbroot"
    String userid = "dbuser";
    String userpasswd = "dbpass";
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(Url,userid,userpasswd);
    
    String sql = "select id,passwd from member where id=?";
    PreparedStatement statement = connection.prepareStatement(sql); // 모든 데이터들을 가져온다는 인터페이스와 연결
    statement.setString(1, id);
    ResultSet set= statement.executeQuery(); // 쿼리 실행
    
    while(set.next()){ // 반복문 시작
        String eqId = set.getString("id"); // 현재 id값을 eqId에 넣음
        String eqPasswd = set.getString("passwd"); // 현재 passwd값을 eqPasswd에 넣음
        
        if(id.equals(eqId) && passwd.equals(eqPasswd)){ // 입력받은값과 현재 넣은걸 비교함
            sql = "update member set name=? where id=?"// name과 id를 ? 로주고 sql쿼리문을 넣음
            statement = connection.prepareStatement(sql); // sql 쿼리문을 연결함
            statement.setString(1, name); // 첫번째 물음표에 name 으로 입력받은 값을넣음
            statement.setString(2, id); // 두번째 물음표에 id값을 넣음
            statement.executeUpdate(); // sql 업데이트
            str = "완료하였습니다.";
            break;
 
        }else{
            str="완료하지 못하였습니다.";
            
        }
        
    }
    
    if(set!=null){ // 객체들 닫기
        set.close();
    }
    if(statement !=null){
        statement.close();
    }
    if(connection !=null){ 
        connection.close();
    }
    
}catch(Exception e){
    e.getStackTrace();
}
 
%>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>변경완료폼</title>
</head>
<body>
<h2>변경을</h2>
 
<%=str%>
 
</body>
</html>
cs

JSP 에서의 레코드 삭제

수정과 삭제는 비슷비슷하다.


삭제가 완료 된걸볼 수 있다.

코드를 보도록하자
07-5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>레코드 삭제 폼</h2>
 
<form action="07-5-1.jsp" method="post">
아이디 : <input type="text" name="id"><br>
패스워드 : <input type="text" name="passwd"><br>
<input type="submit" value="완료">
</form>
 
 
</body>
</html>
cs

07-5-1
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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@page import="java.sql.*"%>
    <%request.setCharacterEncoding("utf-8");%>
    <%!
    
String str;
%>
 
<%
try{
    String id = request.getParameter("id");
    String passwd = request.getParameter("passwd");
    
    String Url = "jdbc:mysql://localhost:3306/dbroot"
    String userid = "dbuser";
    String userpasswd = "dbpass";
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection(Url,userid,userpasswd);
    
    String sql = "select id,passwd from member where id=?";
    PreparedStatement statement = connection.prepareStatement(sql); // 모든 데이터들을 가져온다는 인터페이스와 연결
    statement.setString(1, id);
    ResultSet set= statement.executeQuery(); // 쿼리 실행
    
    while(set.next()){ // 반복문 시작
        String eqId = set.getString("id"); // 현재 id값을 eqId에 넣음
        String eqPasswd = set.getString("passwd"); // 현재 passwd값을 eqPasswd에 넣음
        
        if(id.equals(eqId) && passwd.equals(eqPasswd)){ // 입력받은값과 현재 넣은걸 비교함
            sql = "delete from member where id=?"// name과 id를 ? 로주고 sql쿼리문을 넣음
            statement = connection.prepareStatement(sql); // sql 쿼리문을 연결함
            statement.setString(1, id); // 첫번째 물음표에 id값을 넣음
            statement.executeUpdate(); // sql 업데이트
            str = "완료하였습니다.";
            break;
 
        }else{
            str="완료하지 못하였습니다.";
            
        }
        
    }
    
    if(set!=null){ // 객체들 닫기
        set.close();
    }
    if(statement !=null){
        statement.close();
    }
    if(connection !=null){ 
        connection.close();
    }
    
}catch(Exception e){
    e.getStackTrace();
}
 
%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>삭제</title>
</head>
<body>
<h2>삭제를</h2>
 
<%=str%>
 
</body>
</html>
cs







728x90