JDBC(Java DataBase Connectivity)
- Java에서 DBMS의 종류와 관계없이 데이터베이스를 조작하기 위한
- API(Application Programming Interface)를 의미
- JDBC를 간단하게 요약하면 메소드 호출용 SQL 인터페이스라고 표현할 수 있음
JDBC 드라이버
- 다양한 DBMS 제조사들은 본사에서 개발한 DBMS를 Sun사의 Java 프로그램과연동할 수 있도록 기술을 지원하는 것을 의미
- JDBC는 MySQL 설치과정에서 이미 설치하였으므로 따로 설치할 필요는 없지만 JDBC 드라이버가 어느 폴더에 저장되어 있는지에 대해서는 알고 있어야 함
- JSP프로젝트 내에 lib폴더에 JDBC 드라이버를 추가해준다.
자세한 JDBC에 대한 내용은 아래의 포스트를 참고
2023.08.17 - [Java Category/Java] - [Java] JDBC 개요 및 DB 연결하기
예제 데이터베이스 기본 (MySQL)
JDBC 연결 테스트
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> JDBC 커넥션 테스트 </title>
</head>
<body>
<%
// 1. 변수 4개 선언
String driverName="com.mysql.jdbc.Driver"; //jdbc 드라이버 이름
String url = "jdbc:mysql://localhost:3306/odbo"; //연결 문자열, 마지막은 데이터베이스 이름
String username = "root"; //DB 계정 id
String password = "0000"; //DB 계정 pw
Connection conn = null; //Connection 객체를 null로 레퍼런스
try{
// 2. 드라이버 로딩
Class.forName(driverName); //JDBC 드라이버 메모리에 로딩
// 3. 연동
conn = DriverManager.getConnection(url, username, password); //연결문자열, DB 계정을 Connection객체에 대입
// 4. 여기까지 오류가 없다면 연결 성공
out.println(">> 연결 성공 : " + conn);
} catch(ClassNotFoundException e){
out.println(">> 연결 실패 : 드라이버 복사 필요!");
} catch(SQLException e){
out.println(">> 연결 실패 : SQL 명령문 확인 필요!");
} finally{
// 5. 닫기
try{
if(conn != null)
conn.close();
} catch(SQLException e){
;
}
}
%>
</body>
</html>
회원 가입
signup.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 회원 가입 </title>
</head>
<body>
Home > Signup the Membership
<hr>
<form action="signup_process.jsp" name="user_info" method="post">
<fieldset style="width:200px">
<legend> 회원 가입 </legend><p>
아이디 : <br>
<input type="text" name="userID"><br><br>
비밀번호 : <br>
<input type="password" name="userPW"><br><br>
이메일 : <br>
<input type="email" name="userMAIL"><br><br>
<hr>
<div align="center">
<input type="submit" value=" 가입하기 ">
<input type="reset" value=" 다시작성 ">
</div><br>
</fieldset>
</form>
</body>
</html>
signup_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String u_id = request.getParameter("userID");
String u_pw = request.getParameter("userPW");
String u_mail = request.getParameter("userMAIL");
//INSERT INTO members(id, passwd, email) VALUES( 'idData', 'passwdData', 'emailData' )
String sql = "INSERT INTO members(id, passwd, email) VALUES";
sql += "('" + u_id + "','" + u_pw + "','" + u_mail + "')";
String driverName="com.mysql.jdbc.Driver"; //jdbc 드라이버 이름
String url = "jdbc:mysql://localhost:3306/odbo"; //연결 문자열
String username = "root"; //DB 계정 id
String password = "0000"; //DB 계정 pw
Connection conn = null; //Connection 객체를 null로 레퍼런스
Class.forName(driverName); //JDBC 드라이버 메모리에 로딩
//DriverManager의 정적 메소드인 getConnection는 Connection 객체를 리턴함
conn = DriverManager.getConnection(url, username, password); //연결문자열, DB 계정, Connection객체 대입
//Staement는 변경되지 않는 정적 SQL 문을 실행할 때 사용, 동적 SQL문은 PreparedStatement를 사용
Statement sm = conn.createStatement(); //Statement 얻기
int count = sm.executeUpdate(sql); //쿼리 실행
if(count == 1){ //실행한 쿼리가 1개라면
out.println("회원가입 성공!");
}else{
out.println("회원가입 실패!");
}
sm.close(); //Statement 끊기
conn.close(); //Connection 끊기
%>
성공적으로 DB에 저장된 것을 확인할 수 있다.
회원 탈퇴
withdraw.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> 회원 탈퇴 </title>
</head>
<body>
Home > Withdraw the Membership
<hr>
<form action="withdraw_process.jsp" name="user_info" method="post">
<fieldset style="width:200px">
<legend> 회원 탈퇴 </legend><p>
아이디 : <br>
<input type="text" name="userID"><br>
<div align="center">
<input type="submit" value=" 탈퇴하기 ">
</div><br>
</fieldset>
</form>
</body>
</html>
withdraw_process.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String u_id = request.getParameter("userID");
String sql = "DELETE FROM members WHERE id = ?"; //?에 넣어질 값은 PreparedStatement에서 처리
String driverName="com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/odbo";
String username = "root";
String password = "0000";
Connection conn = null;
Class.forName(driverName);//메모리에 로딩
conn = DriverManager.getConnection(url, username, password); //db에 연결
PreparedStatement sm = conn.prepareStatement(sql); //sql 처리 준비
sm.setString(1, u_id); //첫 번째 ?에 u_id를 대입
int count = sm.executeUpdate(); //sql문을 처리하고 리턴되는 행의 수를 count에 저장
if(count == 1){
out.print("회원 탈퇴 성공!");
}else{
out.print("회원 탈퇴 실패!");
}
sm.close();
conn.close();
%>
성공적으로 DB에서 DELETE문이 이뤄진 것을 확인할 수 있다.
데이터베이스 예제 심화(Oracle SQL)
데이터베이스 구조
DTO (Data Transfer Object)
memberBean.java
더보기
public class MemberBean {
private String id;
private String pass1;
private String email;
private String tel;
private String hobby;
private String job;
private String age;
private String info;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPass1() {
return pass1;
}
public void setPass1(String pass1) {
this.pass1 = pass1;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
DAO (Data Access Object)
memberDAO.java
더보기
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
public class MemberDAO
{
String id = "java";
String pass = "oracle";
String url = "jdbc:oracle:thin:@localhost:1521/orcl";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs; //DB의 테이블 결과를 리턴받아 저장하는 객체
public void getCon()
{
try{
Class.forName("oracle.jdbc.OracleDriver");
conn = DriverManager.getConnection(url, id, pass);
}
catch(Exception e) { e.printStackTrace(); }
}
public void insertMember(MemberBean mbean)
{
try
{
getCon();
String SQL = "INSERT INTO member VALUES(?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1,mbean.getId());
pstmt.setString(2,mbean.getPass1());
pstmt.setString(3,mbean.getEmail());
pstmt.setString(4,mbean.getTel());
pstmt.setString(5,mbean.getHobby());
pstmt.setString(6,mbean.getJob());
pstmt.setString(7,mbean.getAge());
pstmt.setString(8,mbean.getInfo());
pstmt.executeUpdate();
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
}
public Vector<MemberBean> allSelectMember()
{
Vector<MemberBean> v = new Vector<>();
try
{
getCon();
String SQL = "SELECT * FROM member";
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
while(rs.next())
{
MemberBean bean = new MemberBean();
bean.setId(rs.getString(1));
bean.setPass1(rs.getString(2));
bean.setEmail(rs.getString(3));
bean.setTel(rs.getString(4));
bean.setHobby(rs.getString(5));
bean.setJob(rs.getString(6));
bean.setAge(rs.getString(7));
bean.setInfo(rs.getString(8));
v.add(bean);
}
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
return v;
}
public MemberBean oneSelectMember(String id)
{
MemberBean bean = new MemberBean();
try
{
getCon();
String SQL = "SELECT * FROM member WHERE id=?";
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next())
{
bean.setId(rs.getString(1));
bean.setPass1(rs.getString(2));
bean.setEmail(rs.getString(3));
bean.setTel(rs.getString(4));
bean.setHobby(rs.getString(5));
bean.setJob(rs.getString(6));
bean.setAge(rs.getString(7));
bean.setInfo(rs.getString(8));
}
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
return bean;
}
public String getPass(String id)
{
String pass="";
try
{
getCon();
String SQL = "SELECT * FROM member WHERE id=?";
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) pass = rs.getString(2);
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
return pass;
}
public void updateMember(MemberBean bean)
{
try
{
getCon();
String SQL = "UPDATE member SET email=?, tel=? WHERE id=?";
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, bean.getEmail());
pstmt.setString(2, bean.getTel());
pstmt.setString(3, bean.getId());
pstmt.executeQuery();
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
}
public void deleteMember(String id)
{
try
{
getCon();
String SQL = "DELETE FROM member WHERE id=?";
pstmt = conn.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeQuery();
}
catch(Exception e) { e.printStackTrace(); }
finally { if(conn != null) { try { } catch (Exception e) { e.printStackTrace(); } } }
}
}
MemberJoin.jsp
더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h2>회원 가입</h2>
<form action="MemberJoinProc.jsp">
<table width="500" border="1">
<tr height="50">
<td width="150" align="center">아이디 </td>
<td width="350" align="center">
<input type="text" name="id" size="40" placeholder="id를 넣으세요">
</td>
</tr>
<tr height="50">
<td width="150" align="center">패스워드</td>
<td width="350" align="center">
<input type="password" name="pass1" size="40"
placeholder="비밀번호는 숫자와 영어만 넣어주세요">
</td>
</tr>
<tr height="50">
<td width="150" align="center">패스워드 확인</td>
<td width="350" align="center">
<input type="password" name="pass2" size="40">
</td>
</tr>
<tr height="50">
<td width="150" align="center">이메일</td>
<td width="350" align="center">
<input type="email" name="email" size="40">
</td>
</tr>
<tr height="50">
<td width="150" align="center">전화 번호 </td>
<td width="350" align="center">
<input type="tel" name="tel" size="40">
</td>
</tr>
<tr height="50">
<td width="150" align="center">당신의 관심 분야</td>
<td width="350" align="center">
<input type="checkbox" name="hobby" value="캠핑">캠핑
<input type="checkbox" name="hobby" value="등산">등산
<input type="checkbox" name="hobby" value="독서">독서
<input type="checkbox" name="hobby" value="음악">음악
</td>
</tr>
<tr height="50">
<td width="150" align="center">당신의 직업은</td>
<td width="350" align="center">
<select name="job">
<option value="교사">교사</option>
<option value="의사">의사</option>
<option value="변호사">변호사</option>
<option value="기술사">기술사</option>
</select>
</td>
</tr>
<tr height="50">
<td width="150" align="center">당신의 연령은</td>
<td width="350" align="center">
<input type="radio" name="age" value="10">10대
<input type="radio" name="age" value="20">20대
<input type="radio" name="age" value="30">30대
<input type="radio" name="age" value="40">40대
</td>
</tr>
<tr height="50">
<td width="150" align="center">하고 싶은말</td>
<td width="350" align="center">
<textarea rows="5" cols="40" name="info"></textarea>
</td>
</tr>
<tr height="50" align="center">
<td width="150" colspan="2">
<input type="submit" value="회원 가입">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
MemberJoinProc.jsp
더보기
<%@page import="model.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
request.setCharacterEncoding("UTF-8");
String hobby[] = request.getParameterValues("hobby");
String textHobby = "";
for(int i = 0; i < hobby.length; ++i) textHobby += hobby[i] + " ";
%>
<jsp:useBean id="mbean" class="model.MemberBean">
<jsp:setProperty name="mbean" property="*"/>
</jsp:useBean>
<%
mbean.setHobby(textHobby);
MemberDAO mdao = new MemberDAO();
mdao.insertMember(mbean);
response.sendRedirect("MemberList.jsp");
%>
</body>
</html>
MemberList.jsp
더보기
<%@page import="model.MemberBean" %>
<%@page import="model.MemberDAO" %>
<%@page import="java.util.Vector" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
MemberDAO mdao = new MemberDAO();
Vector<MemberBean> vec = mdao.allSelectMember();
%>
<center>
<h2>모든 회원 정보</h2>
<table width="800" border="1">
<tr height="50">
<td align="center" width="150">아이디</td>
<td align="center" width="250">이메일</td>
<td align="center" width="200">전화번호</td>
<td align="center" width="200">취미</td>
</tr>
<%
for(int i = 0; i < vec.size(); ++i)
{
MemberBean bean = vec.get(i);
%>
<tr height="50">
<td align="center" width="150"><a href="MemberInfo.jsp?id=<%= bean.getId() %>"><%= bean.getId() %></a></td>
<td align="center" width="250"><%= bean.getEmail() %></td>
<td align="center" width="200"><%= bean.getTel() %></td>
<td align="center" width="200"><%= bean.getHobby() %></td>
</tr>
<%}%>
</table>
</center>
</body>
</html>
MemberUpdateForm.jsp
더보기
<%@page import="model.MemberBean"%>
<%@page import="model.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
String id = request.getParameter("id");
MemberDAO mdao = new MemberDAO();
MemberBean mbean = mdao.oneSelectMember(id);
%>
<center>
<h2>회원 정보</h2>
<table width="400" border="1">
<form action="MemberUpdateProc.jsp" method="post">
<tr height="50">
<td align="center" width="150">아이디</td>
<td width="250"><%= mbean.getId() %></td>
</tr>
<tr height="50">
<td align="center" width="150">이메일</td>
<td width="250"><input type="email" name="email" value="<%= mbean.getEmail() %>"></td>
</tr>
<tr height="50">
<td align="center" width="150">전화</td>
<td width="250"><input type="tel" name="tel" value="<%= mbean.getTel() %>"></td>
</tr>
<tr height="50">
<td align="center" width="150">패스워드</td>
<td width="250"><input type="password" name="pass1"></td>
</tr>
<tr height="50">
<td align="center" colspan="2">
<input type="hidden" name="id" value="<%= mbean.getId() %>">
<input type="submit" value="회원 수정하기">
</form>
<button onclick="location.href='MemberList.jsp'">회원 전체 보기</button>
</td>
</tr>
</table>
</center>
</body>
</html>
MemberUpdateProc.jsp
더보기
<%@page import="model.MemberDAO"%>
<%@page import="model.MemberBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
<jsp:useBean id="mbean" class="model.MemberBean">
<jsp:setProperty name="mbean" property="*"/>
</jsp:useBean>
<%
MemberDAO mdao = new MemberDAO();
String pass = mdao.getPass(mbean.getId());
if(mbean.getPass1().equals(pass))
{
mdao.updateMember(mbean);
response.sendRedirect("MemberList.jsp");
}
else
{
%>
<script type="text/javascript">
alert("패스워드가 맞지 않습니다. 다시 확인해 주세요")
history.go(-1);
</script>
<%
}
%>
</body>
</html>
MemberInfo.jsp
더보기
<%@page import="model.MemberBean" %>
<%@page import="model.MemberDAO" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
String id = request.getParameter("id");
MemberDAO mdao = new MemberDAO();
MemberBean mbean = mdao.oneSelectMember(id);
%>
<center>
<h2>회원 정보</h2>
<table width="400" border="1">
<tr height="50">
<td align="center" width="150">아이디</td>
<td width="250"><%= mbean.getId() %></td>
</tr>
<tr height="50">
<td align="center" width="150">이메일</td>
<td width="250"><%= mbean.getEmail() %></td>
</tr>
<tr height="50">
<td align="center" width="150">전화</td>
<td width="250"><%= mbean.getTel() %></td>
</tr>
<tr height="50">
<td align="center" width="150">취미</td>
<td width="250"><%= mbean.getHobby() %></td>
</tr>
<tr height="50">
<td align="center" width="150">직업</td>
<td width="250"><%= mbean.getJob() %></td>
</tr>
<tr height="50">
<td align="center" width="150">나이</td>
<td width="250"><%= mbean.getAge() %></td>
</tr>
<tr height="50">
<td align="center" width="150">정보</td>
<td width="250"><%= mbean.getInfo() %></td>
</tr>
<tr height="50">
<td align="center" colspan="2">
<button onclick="location.href='MemberUpdateForm.jsp?id=<%=mbean.getId()%>'">회원수정</button>
<button onclick="location.href='MemberDeleteForm.jsp?id=<%=mbean.getId()%>'">회원삭제</button>
<button onclick="location.href='MemberList.jsp?id=<%=mbean.getId()%>'">목록보기</button>
<button onclick="location.href='MemberJoin.jsp?id=<%=mbean.getId()%>'">회원가입</button>
</td>
</tr>
</table>
</center>
</body>
</html>
MemberDeleteForm.jsp
더보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<center>
<h2>회원 삭제 하기</h2>
<table width="400" border="1">
<form action="MemberDeleteProc.jsp" method="post">
<tr height="50">
<td align="center" width="150">아이디</td>
<td width="250"><%= request.getParameter("id") %></td>
</tr>
<tr height="50">
<td align="center" width="150">패스워드</td>
<td width="250"><input type="password" name="pass1"></td>
</tr>
<tr height="50">
<td align="center" colspan="2">
<input type="hidden" name="id" value="<%= request.getParameter("id") %>">
<input type="submit" value="회원 삭제하기">
</form>
<button onclick="location.href='MemberList.jsp'">회원 전체 보기</button>
</td>
</tr>
</table>
</center>
</body>
</html>
MemberDeleteProc.jsp
더보기
<%@page import="model.MemberDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<%
request.setCharacterEncoding("UTF-8");
%>
<jsp:useBean id="mbean" class="model.MemberBean">
<jsp:setProperty name="mbean" property="*"/>
</jsp:useBean>
<%
MemberDAO mdao = new MemberDAO();
String pass = mdao.getPass(mbean.getId());
if(mbean.getPass1().equals(pass))
{
mdao.deleteMember(mbean.getId());
response.sendRedirect("MemberList.jsp");
}
else
{
%>
<script type="text/javascript">
alert("패스워드가 맞지 않습니다. 다시 확인해 주세요")
history.go(-1);
</script>
<%
}
%>
</body>
</html>
'Java Category > JSP' 카테고리의 다른 글
[JSP] IntelliJ 에서 JSP 개발환경 만들기 (1) | 2024.01.08 |
---|---|
[JSP] 파일 업로드 (0) | 2023.12.25 |
[JSP] 액션 태그(Action tag) (1) | 2023.11.27 |
[JSP] 세션(Session) (1) | 2023.11.25 |
[JSP] 쿠키(Cookie) (2) | 2023.11.24 |