[학교 공부][JSP]-JDBC로 JSP와 데이터베이스 연결

Mini_me·2021년 12월 2일
0

공부 [JSP] 

목록 보기
9/11

JDBC ? 그게뭐야?

정의

자바 표준 인터페이스로, 자바/JSP 프로그램 내에서 데이터 베이스와 관련된 작업을 처리할 수 있도록 도와주는 자바 표준 인터페이스이다.
sql문을 실행하기 위한 자바 API / 자바 라이브러리로, JDBC API를 사용할 경우, DBMS의 종류랑 상관없이 데이터 베이스 작업을 처리할 수 있다.

JDBC을 사용한 JSP와 데이터 베이스의 연동

❶ java.sql.* 패키지 임포트
❷ JDBC 드라이버 로딩
❸ 데이터베이스 접속을 위한 Connection 객체 생성
❹ 쿼리문을 실행하기 위한 Statement/PreparedStatement/CallableStatement
객체 생성
❺ 쿼리 실행
❻ 쿼리 실행의 결과 값(int, ResultSet) 사용
❼ 사용된 객체(ResultSet, Statement/PreparedStatement/CallableStatement, Connection) 종료

다음 코드는 웹 홈페이지 프로젝트 구현 시, 로그인 처리 과정에서 사용했던 코드입니다.

Connection conn=null;
String dbURL = "jdbc:mysql://localhost:3306/flowershop?characterEncoding=euckr";
String dbID = "root";
String dbPassword = "1234";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbID, dbPassword);

				ResultSet rs=null;
				PreparedStatement pstmt=null;
				
				try {
					String sql = "select userID,userPassword from user where userID =?";
					
					pstmt = conn.prepareStatement(sql); 
				
				pstmt.setString(1,userID);
				rs=pstmt.executeQuery();
					if(rs.next()) { //다음 행으로 커서 이동 
					String rId=rs.getString("userID");
					String rPasswd=rs.getString("userPassword");
					if(userID.equals(rId)&&userPassword.equals(rPasswd)){
					session.setAttribute("userID", userID);
						out.println("<script> alert('로그인 성공') </script>");  // 일치하면 로그인성공
						out.println("<script> location.href='welcome.jsp' </script>"); 
						
					}
							else
							out.println("<script> alert('비밀번호가 틀렸습니다.') </script>");  //비밀번호가 틀렸으므로 비밀번호 틀립니다 출력 
					}
					else
					 out.println("<script> alert('아이디가 존재하지 않습니다.') </script>");  //존재하지 않는 아이디 출력 
				}catch (SQLException ex) {
				out.println("SQLException: "+ex.getMessage());
				}
				finally {
					if(rs!=null)
						rs.close();
					if(pstmt!=null)
						pstmt.close();
					if(conn!=null)
						conn.close();
			
			}
		%>

이제 코드를 분석하며 JDBC를 어떻게 적용했는지 보여드리겠습니다.

1. JDBC 로딩하기

Connection conn=null;
String dbURL = "jdbc:mysql://localhost:3306/flowershop?characterEncoding=euckr";
String dbID = "root";
String dbPassword = "1234";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbID, dbPassword);

Class.forName("com.mysql.jdbc.Driver");
Class.forName()을 이용하여 JDBC 드라이버를 로딩한다.
JDBC 드라이버가 로딩되면 자동으로 객체가 생성
DriverManager 클래스에 등록한다.
이렇게 JDBC 드라이버 로딩하는 과정은 프로그램 수행 시 한번만 필요하다.

2. Connection 객체 생성하기

Connection conn=null;
DriverManager.getConnection(dbURL, dbID, dbPassword);

JDBC 드라이버에서 데이터 베이스와 연결된 커넥션을 가져오기 위해 DriverManager 클래스의 getConnection()메소드를 사용한다.

객체 생성 시, JDBC 드라이버를 검색하고, 검색된 드라이버를 이용하여 Connection 객체를 생성한 후 이를 반환한다.

com.mysql.jdbc.Driver 드라이버를 검색하여 connection 개체(conn)을 생성하여 반환한다.

3.데이터 베이스 연결 닫기

finally {
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(conn!=null)
conn.close(); }

데이터 베이스 연결이 필요하지 않을 경우,
close() 메소드 사용하여 생성햇던 Connection을 해제해야 한다.
일반적으로는 데이터베이스 리소스를 사용하지 않기 위해 사용을 끝내자마자 리소스를 해제하는 것이 좋다.

데이터 베이스 쿼리 실행

statement 객체

1) 정적인 쿼리에 사용
2) 하나의 쿼리를 사용 -> 더이상 사용불가
3) 하나의 쿼리 끝냄-> close()로 해재
즉시 해제하지 않을 경우 : 무시할 수 없는 공간 필요-> 페이지가 다른 작업 수행하는 동안 멈추지 않음
4) 복잡하지 않은 간단한 쿼리문 사용할 경우 좋다.

PreparedStatement 객체

1) 동적인 쿼리에 사용
2) 하나의 객체로 여러번의 쿼리 실행 가능
-> 동일 쿼리문을 특정 값만 바꿔서 여러번 실행해야 할 때, 매개변수가 많아서 쿼리문 정리해야할 때 유용

 PreparedStatement pstmt=null;
					
  try {
	String sql = "select userID,userPassword from user where userID =?";
						
	pstmt = conn.prepareStatement(sql);
rs=pstmt.executeQuery();
						if(rs.next()) { //다음 행으로 커서 이동 
						String rId=rs.getString("userID");
						String rPasswd=rs.getString("userPassword");
						if(userID.equals(rId)&&userPassword.equals(rPasswd)){
						session.setAttribute("userID", userID);
							out.println("<script> alert('로그인 성공') </script>");  // 일치하면 로그인성공
							out.println("<script> location.href='welcome.jsp' </script>"); 
							
						}
  • excuteUpdate() 메소드를 이용하여, 데이터 삽입 및 수정 ,삭제하였다.

ResultSet 객체

Statement / PreparedStatement 객체로 select 문ㅇ르 사용하여 얻어온 레코드 값을 테이블 형태로 가진 객체

ResultSet rs=null;
rs=pstmt.executeQuery();
		if(rs.next()) { //다음 행으로 커서 이동 
						String rId=rs.getString("userID");
						String rPasswd=rs.getString("userPassword");
						if(userID.equals(rId)&&userPassword.equals(rPasswd)){
						session.setAttribute("userID", userID);
							out.println("<script> alert('로그인 성공') </script>");  // 일치하면 로그인성공
							out.println("<script> location.href='welcome.jsp' </script>"); 
							
						}
								else
								out.println("<script> alert('비밀번호가 틀렸습니다.') </script>");  //비밀번호가 틀렸으므로 비밀번호 틀립니다 출력 
						}
						else
						 out.println("<script> alert('아이디가 존재하지 않습니다.') </script>");  //존재하지 않는 아이디 출력 
					}catch (SQLException ex) {
					out.println("SQLException: "+ex.getMessage());
					}
					finally {
						if(rs!=null)
							rs.close();

PreparedStatement 객체로 select문을 이용하여 얻어온 레코드 값(userID, userPassword)을 Result 객체를 이용하여 폼에 입력된 userID와 userPasword값을 비교해 로그인 알림창을 띄운다.

0개의 댓글

관련 채용 정보