JSP 기본 08

이정우·2021년 10월 27일
1

JSP

목록 보기
9/10

JSP와 DB 연결하기

1.JDBC 드라이버 로드(DriverManager)
2.데이터베이스와 연결(Connection)
3.SQL문 실행(Statement)
4.데이터베이스와 연결 끊기(ResultSet)

JSP와 DB 연결하기 실습

  1. ojdbc6.jar 파일을 프로젝트 WEB-INF > lib 폴더 아래에 넣어준다.
  2. 아래와 같은 jsp파일을 작성한다.
    코드 설명은 따로 쓰는것 보다 보기 편하게 주석 형식으로 작성함.
<%@page import = "java.sql.*" %>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%! //선언부는 첫 방문자에 의해서 단 한번 수행합니다.
//java.sql객체에 존재하는 connection statement, resultset등을 쓴다.
Connection conn = null; //db와 연결!
Statement stmt = null; //표준 쿼리문을 지키기 위해 사용되는 변수
ResultSet rs = null; //sql 쿼리문을 보내서 결과를 저장할 변수
//ResultSet객체는 결과를 얻어오면 테이블에서 첫 칸은 BOF(Begin Of File)으로 빈 칸으로 놔두고 마지막 칸을 EOF(End Of File)으로 놔둔다.

String url = "jdbc:oracle:thin:@localhost:1521:XE"; //localhost는 db ip. 1521은 오라클에서 자주 사용하는 포트 번호. xe는 오라클 서비스 이름.
String uid = "아이디";
String pass = "비번";
String sql = "select * from MEMBER";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
<table width = '800' border = '1'>
<tr>
	<th>이름</th><th>아이디</th><th>암호</th><th>이메일</th><th>전화번호</th><th>권한(1:관리자, 0:일반회원)</th>
</tr>
<%
try {
	Class.forName("oracle.jdbc.driver.OracleDriver"); //jdbc 드라이버 이름. ms-sql, mysql은 다른 이름이 존재.  jdbc 드라이버 로딩!
	conn = DriverManager.getConnection(url, uid, pass); //로딩된 드라이버를 갖고 db와 연결을 해서 작업을 수행할 수 있게 해주는 객체(connection). 잘 보면 url 기반으로 id, pwd 입력중
	stmt = conn.createStatement(); //conn의 createStatement메소드를 통해 결과값을 stmt에 저장. 그 이유는 statement객체가 sql 표준 쿼리문을 수행하기 위해서 사용되기 때문.
	rs = stmt.executeQuery(sql); //쿼리문을 조회하기 시작. select문은 이 메서드를 사용하고 insert update delete같은 내부적으로 테이블 내용을 변경하고 결과 값이 없는 경우는 executeUpdate()메서드 사용.
	while(rs.next()) { //BOF, EOF는 빈 공간. 즉 마지막 칸인 EOF가 오면 false값이 와서 while문 종료.
		out.println("<tr>");
		out.println("<td>" + rs.getString("name") + "</td>"); //getString(1)이렇게 index명으로도 가능은 함. 순서대로 1,2,3... 하지만 가독성 면이랑 처리 속도 면에서 컬럼 이름을 정확히 명시해주는게 컴퓨터 처리 속도가 빠르기도 빠르고 알아 보기도 편함.
		out.println("<td>" + rs.getString("userid") + "</td>");
		out.println("<td>" + rs.getString("pwd") + "</td>");
		out.println("<td>" + rs.getString("email") + "</td>");
		out.println("<td>" + rs.getString("phone") + "</td>");
		out.println("<td>" + rs.getInt("admin") + "</td>");
		out.print("</tr>");
	}//while 끝 부분
}catch(Exception e) {
	e.printStackTrace();
}finally {
	try {
		if(rs != null) rs.close();
		if(stmt != null) stmt.close();
		if(conn != null) conn.close();
	}catch (Exception e) {
		e.printStackTrace();
	}
}//finally 끝 부분
%>
</table>
</body>
</html>

출처 : 국비 교육

profile
프로그래밍 공부 중!

0개의 댓글