[JSP]JDBC

UnKnown_7·2022년 10월 5일

JSP&Servlet

목록 보기
9/13

설치방법

다운로드

https://dev.mysql.com/downloads/connector/j/

  • OS:Platform Independent로 zip을 다운받는다.
  • 압출파일 안의 mysql-connector-java-8.0.30.jar을 프로젝트 폴더의 WEB-INF/lib 안에 넣는다.
  • properties > java build path > Class path > Add jars로 lib안에 넣은 mysql-connector-java-8.0.30.jar를 선택하고 포함시킨다.

구문 모음

  1. Connection Establish
    • conn: Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD)
  2. Prepare Statement
    • pstmt: pstmt = conn.prepareStatement(query);
  3. Execute Statement
    • No return: pstmt.executeUpdate();
    • ResultSet return: ResultSet rs = pstmt.executeQuery();

DB연결 테스트

예시
DB_Conn.jsp로 활용


<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page import="java.sql.*" %>      <!-- import : java.sql.* -->
 
<%
    String ID = "root";                         // MySQL 아이디
    String PWD= "PW";                         // MySQL 비밀번호
    String PORTNO = "3306";                     // MySQL 포트 번호
    String DBNAME = "dbtest";                     // 연결할 MySQL DB 이름
    String TIMEZONE = "serverTimezone=UTC";     // MySQL 8.0 버전 이상 연결 시 사용
 
    String Query = "jdbc:mysql://localhost:" + PORTNO + "/" + DBNAME + "?" + TIMEZONE;                                             
 
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(Query, ID, PWD);  
    /*
    if (conn != null) {
        out.println("WebDB 데이터베이스로 연결했습니다. <br>");
        conn.close();
        out.println("WebDB 데이터베이스로의 연결을 끊었습니다.<br>");
    }
    else {
        out.println("WebDB 데이터베이스로 연결할 수 없습니다.<br>");
    }*/
%>

DB에 값 넣기

DB_Conn.jsp include로 연결

일반적인 state로 삽입 예시

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>

<title>데이터 베이스 연동하기</title>
</head>
<body>
	<!-- 파일 가져오기 -->
	<%@ include file="DB_Conn.jsp" %>
	<%
		// 폼에서 넘어온 자료 받기
		request.setCharacterEncoding("utf-8");
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String name = request.getParameter("name");
		
		Statement stmt = null;
		
		try {
			String sql = "insert into member(id, passwd, name) values('"+id+"','"+pw+"','"+name+"')";
			stmt = conn.createStatement();
			// 삽입 수정 삭제는 update로 실행해준다
			stmt.executeUpdate(sql);
			out.print("member 테이블 삽입에 성공했습니다");
		} catch (SQLException e) {
			out.print("member 테이블에 삽입이 실패하였습니다 <br>");
			out.print("SQLException: " + e.getMessage());
		} finally {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	%>
</body>
</html>

prepare statement를 통한 삽입 예시

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>

<title>데이터 베이스 연동하기</title>
</head>
<body>
	<p> PrepareStatement 객체 사용 </p>
	
		<!-- 파일 가져오기 -->
	<%@ include file="DB_Conn.jsp" %>
	<%
		// 폼에서 넘어온 자료 받기
		request.setCharacterEncoding("utf-8");
		String id = request.getParameter("id");
		String pw = request.getParameter("pw");
		String name = request.getParameter("name");
		
		// PreparedStatement 를 불러오고
		PreparedStatement pstmt = null;
		
		try {
        		// 여기 모양이 다르다. 위에서는 ?를 보내고
			String sql = "insert into member(id, passwd, name) values(?,?,?)";
			pstmt = conn.prepareStatement(sql);
            		// 첫번째 ? 에는 id가 들어갈 것이다
			pstmt.setString(1, id);
            		// 두번째 ? 에는 pw가 들어갈 것이다
			pstmt.setString(2, pw);
            		// 세번째 ? 에는 name이 들어갈 것이다
			pstmt.setString(3, name);
			pstmt.executeUpdate();

			out.print("member 테이블 삽입에 성공했습니다");
		} catch (SQLException e) {
			out.print("member 테이블에 삽입이 실패하였습니다 <br>");
			out.print("SQLException: " + e.getMessage());
		} finally {
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	%>
</body>
</html>

DB에서 값 추출하기

DB_Conn.jsp include로 연결

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>

<title>검색</title>
</head>
<body>
	<p> 서버쪽에서 받은 내용을 검색해 가져오기 </p>
	<%@ include file="DB_Conn.jsp" %>
	
	<table width="300" border="1">
		<tr>
			<th> 아이디 </th>
			<th> 비밀번호 </th>
			<th> 이름 </th>
		</tr>
		<%
			ResultSet rs = null;
			PreparedStatement pstmt = null;
			
			try{
				String sql = "select * from member";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
			
				while(rs.next()){
					String id = rs.getString("id");
					String passwd = rs.getString("passwd");
					String name = rs.getString("name");
		%>
		<tr>
			<td><%= id %></td>
			<td><%= passwd %></td>
			<td><%= name %></td>
		</tr>
		<%
					}
				} catch (SQLException e) {
					out.print("member 테이블 호출에 실패 <br>");
					out.print("SQLException: " + e.getMessage());
				} finally {
					if (rs != null) rs.close();
					if (pstmt != null) pstmt.close();
					if (conn != null) conn.close();
				}
		%>
	</table>
</body>
</html>
profile
개인 공부 요약용 블로그

0개의 댓글