close( )
를 사용하여 객체를 즉시 해제해야 함close( )
를 사용하여 객체를 즉시 해제하지 않으면 무시할 수 없는 공간이 필요하며 페이지가 다른 작업을 수행하는 동안 멈추지 않기 때문(메모리를 많이 잡아먹음)dbconn.jsp
<%-- dbconn--%>
<%@ page import="java.sql.*" %>
<%
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/javadb";
String user = "test1";
String passwd = "java505";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, passwd);
%>
insert02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기</title>
</head>
<body>
<form action="insert02_process.jsp" method="post">
<label for="user-id">아이디 : </label>
<input type="text" id="user-id" name="userId"><br>
<label for="user-pw">비밀번호 : </label>
<input type="text" id="user-pw" name="userPw"><br>
<label for="user-name">이름 : </label>
<input type="text" id="user-name" name="userName"><br>
<button type="submit">전송</button>
</form>
</body>
</html>
insert02_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Stack" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<%
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String userPw = request.getParameter("userPw");
String userNm = request.getParameter("userName");
Statement stmt = null;
try {
String sql = "INSERT INTO member (id, passwd, name)";
sql += "Values ('" + userId + "', '" + userPw + "', '" + userNm + "') ";
stmt = conn.createStatement();
stmt.executeUpdate(sql);
out.println("member 테이블에 데이터를 추가하였습니다.");
}
catch (SQLException e) {
out.print("member 테이블에 데이터 추가를 실패하였습니다.");
out.print("SQLException : " + e.getMessage());
}
finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</body>
</html>
setXxx()
메소드의 종류데이터 조회
INSERT, UPDATE, DELETE 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용
dbconn.jsp
<%-- dbconn--%>
<%@ page import="java.sql.*" %>
<%
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/javadb";
String user = "test1";
String passwd = "java505";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, passwd);
%>
insert03.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - PreparedStatement</title>
</head>
<body>
<form action="insert03_process.jsp" method="post">
<label for="user-id">아이디 : </label>
<input type="text" id="user-id" name="userId"><br>
<label for="user-pw">비밀번호 : </label>
<input type="text" id="user-pw" name="userPw"><br>
<label for="user-name">이름 : </label>
<input type="text" id="user-name" name="userName"><br>
<button type="submit">전송</button>
</form>
</body>
</html>
insert03_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - PreparedStatement</title>
</head>
<body>
<%@ include file="dbconn.jsp" %>
<%
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String userPw = request.getParameter("userPw");
String userNm = request.getParameter("userName");
PreparedStatement pstmt = null;
try {
// 쿼리문 쓸때는 끝에 띄어쓰기 1칸 해주기! 습관들이자!
String sql = "INSERT INTO member (id, passwd, name) ";
sql += "VALUES (?, ?, ?) ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
pstmt.setString(2, userPw);
pstmt.setString(3, userNm);
pstmt.executeUpdate();
out.println("member 테이블에 데이터를 추가하였습니다.");
}
catch (SQLException e) {
out.println("member 테이블에 데이터 추가를 실패했습니다.");
out.println("SQLException : " + e.getMessage());
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</body>
</html>
Statement 또는 PreparedStatement 객체로 SELECT 문을 사용하여 얻어온 레코드 값을 테이블 형태로 가진 객체
ResultSet 객체의 메소드 종류
Statement에서 executeQuery() 사용
select01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sound.midi.MidiFileFormat" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - Statement(select)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<div class="container mt-4">
<div class="row">
<div class="col-sm-6 mx-auto">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>아이디</th>
<th>비밀번호</th>
<th>이름</th>
</tr>
</thead>
<tbody>
<%
ResultSet rs = null;
Statement stmt = null;
try {
String sql = "SELECT * FROM member ";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
// dbconn 의 변수와 동일한 변수를 쓰면 안됨 (passwd 사용x)
String userId = rs.getString("id"); //varChar
String userPw = rs.getString("passwd"); //varChar
String userNm = rs.getString("name"); //varChar
%>
<tr>
<td><%=userId%></td>
<td><%=userPw%></td>
<td><%=userNm%></td>
</tr>
<%
}
}
catch (SQLException e) {
out.println("member 테이블의 데이터 조회가 실패했습니다.");
out.println("SQLException : " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
PreparedStatement에서 executeQuery() 사용 (SELECT)
select02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - PreparedStatement (select)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<div class="container mt-4">
<div class="row">
<div class="col-sm-6 mx-auto">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>아이디</th>
<th>비밀번호</th>
<th>이름</th>
</tr>
</thead>
<tbody>
<%
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM member ";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
String userId = rs.getString("id");
String userPw = rs.getString("passwd");
String userNm = rs.getString("name");
%>
<tr>
<td><%=userId%></td>
<td><%=userPw%></td>
<td><%=userNm%></td>
</tr>
<%
}
}
catch (SQLException e) {
out.println("member 테이블 데이터 조회가 실패했습니다.");
out.println("SQLException : " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Statement에서 executeQuery() 사용 (UPDATE)
id, pw 가 일치하면 name 변경 가능함
update01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - Statement (update)</title>
</head>
<body>
<form action="update01_process.jsp" method="post">
<label for="user-id">아이디</label>
<input type="text" id="user-id" name="userId"><br>
<label for="user-pw">비밀번호</label>
<input type="text" id="user-pw" name="userPw"><br>
<label for="user-name">이름</label>
<input type="text" id="user-name" name="userName"><br>
<button type="submit">업데이트</button>
</form>
</body>
</html>
update01_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - Statement (update)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<%
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String userPw = request.getParameter("userPw");
String userNm = request.getParameter("userName");
Statement stmt = null;
ResultSet rs = null;
try {
String sql = "SELECT id, passwd FROM member ";
sql += "WHERE id = '" + userId + "' ";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
String rid = rs.getString("id");
String rpw = rs.getString("passwd");
// 새로 추가
if (userId.equals(rid) && userPw.equals(rpw)) {
sql = "UPDATE member SET name = '" + userNm + "' ";
sql += "WHERE id = '" + userId + "' ";
stmt = conn.createStatement();
stmt.executeUpdate(sql);
out.println("member 테이블의 데이터를 수정하였습니다.");
}
else {
out.println("비밀번호가 틀렸습니다.");
}
}
else {
out.println("일치하는 사용자가 없습니다.");
}
}
catch (SQLException e) {
out.println("SQLException : " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</body>
</html>
PreparedStatement에서 executeQuery() 사용 (UPDATE)
update02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - PreparedStatement (update)</title>
</head>
<body>
<form action="update02_process.jsp" method="post">
<label for="user-id">아이디</label>
<input type="text" id="user-id" name="userId"><br>
<label for="user-pw">비밀번호</label>
<input type="text" id="user-pw" name="userPw"><br>
<label for="user-name">이름</label>
<input type="text" id="user-name" name="userName"><br>
<button type="submit">업데이트</button>
</form>
</body>
</html>
update02_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>DB 사용하기 - PreparedStatement (update)</title>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<%
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String userPw = request.getParameter("userPw");
String userNm = request.getParameter("userName");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT id, passwd FROM member ";
sql += "WHERE id = ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
if (rs.next()) {
String rid = rs.getString("id");
String rpw = rs.getString("passwd");
if (userId.equals(rid) && userPw.equals(rpw)) {
sql = "UPDATE member SET name = ? ";
sql += "WHERE id = ? ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, userNm);
pstmt.setString(2, userId);
pstmt.executeUpdate();
out.println("member 테이블의 정보를 수정하였습니다.");
}
else {
out.println("비밀번호가 틀렸습니다.");
}
}
else {
out.println("일치하는 사용자가 없습니다.");
}
}
catch (SQLException e) {
out.println("SQLException = " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</body>
</html>
delete01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>문제1. Statement를 사용하여 DELETE 를 실행하는 프로그램 작성</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="delete01_process.jsp">
<label for="user-id">아이디</label>
<input type="text" id="user-id" name="userId"><br>
<label for="user-pw">비밀번호</label>
<input type="text" id="user-pw" name="userPw"><br>
<button type="submit">삭제</button>
</form>
</body>
</html>
delete01_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>문제1. Statement를 사용하여 DELETE 를 실행하는 프로그램 작성</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<%
request.setCharacterEncoding("UTF-8");
String userId = request.getParameter("userId");
String userPw = request.getParameter("userPw");
Statement stmt = null;
ResultSet rs = null;
try {
// sql문 지정
// id 검색
String sql = "SELECT id, passwd FROM member ";
sql += "WHERE id = '" + userId + "' ";
// conn 객체 사용하여 Statement 객체 생성해줌 => dbconn에 연결
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// if문으로 확인한 이유 : id(pk키)로 검색했을때는 결과가 단 2개. 있거나 없거나. 있으면 true, 없으면 false
if (rs.next()) {
String rid = rs.getString("id");
String rpw = rs.getString("passwd");
if (userId.equals(rid) && userPw.equals(rpw)) {
// DELETE 구문 생성
sql = "DELETE FROM member ";
sql += "WHERE id = '" + userId + "' ";
// 기존 객체 버리고 새 객체 생성
stmt = conn.createStatement();
// executeUpdate()를 이용해서 DELETE문 실행
stmt.executeUpdate(sql);
out.println("member 테이블의 데이터를 삭제했습니다.");
}
else {
out.println("비밀번호가 틀렸습니다.");
}
}
else {
out.println("지정한 사용자가 없습니다..");
}
}
catch (SQLException e) {
out.println("member테이블의 데이터를 삭제하지 못했습니다.");
out.println("SQLException : " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</body>
</html>
글 쓰고 글 내리는 형식 (id, pw 기능 없이)
boardList.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%@ include file="dbconn.jsp"%>
<header class="container mt-3">
<div class="p-5 mb-4 bg-light rounded-3">
<div class="container-fluid py-4">
<h1 class="text-center">게시물 리스트 페이지</h1>
</div>
</div>
</header>
<main class="container mt-4">
<div class="row">
<div class="col-sm">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>글번호</th>
<th>글제목</th>
<th>글쓴이</th>
<th>등록시간</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<%
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 전체 글 조회 쿼리문
String sql = "SELECT seq, title, user_id, create_date, cnt FROM board WHERE deleted_yn = 'N' ";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
int seq = rs.getInt("seq");
String title = rs.getString("title");
String userId = rs.getString("user_id");
String createDt = rs.getString("create_date");
int cnt = rs.getInt("cnt");
%>
<tr>
<td><%=seq%>></td>
<td><%=title%></td>
<td><%=userId%></td>
<td><%=createDt%></td>
<td><%=cnt%></td>
</tr>
<%
}
}
catch (SQLException e) {
out.println("SQLException : " + e.getMessage());
}
finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
%>
</tbody>
</table>
<div class="d-flex justify-content-end">
<a href="boardWrite.jsp" class="btn btn-primary">글쓰기</a>
</div>
</div>
</div>
</main>
<footer class="container-fluid mt-5 p-5 border-top">
<p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>
</html>
boardWrite.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>게시판 글쓰기 페이지</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
<%-- 자바스크립트 --%>
window.addEventListener('DOMContentLoaded', function () {
const btnBack = document.querySelector('#btn-back');
btnBack.addEventListener('click', function () {
//뒤로가기 기능
history.back();
})
});
</script>
</head>
<body>
<header class="container mt-3">
<div class="p-5 mb-4 bg-light rounded-3">
<div class="container-fluid py-4">
<h1 class="text-center">게시물 글쓰기 페이지</h1>
</div>
</div>
</header>
<main class="container mt-5">
<div class="row">
<div class="col-sm-6 mx-auto">
<form action="boardWrite_process.jsp" method="post" class="border rounded-3 p-4">
<div class="form-floating my-3">
<input type="text" class="form-control" id="title" name="title" placeholder="제목을 입력하세요">
<label for="title" class="form-label">Title</label>
</div>
<div class="form-floating my-3">
<input type="text" class="form-control" id="user-id" name="userId" placeholder="ID를 입력하세요">
<label for="user-id" class="form-lavel">ID</label>
</div>
<div class="form-floating my-3">
<textarea class="form-control" id="contents" name="contents" placeholder="내용을 입력하세요" ></textarea>
<label for="contents" class="form-label">Contents...</label>
</div>
<div class="d-grid gap-2">
<button class="btn btn-primary" type="submit">글쓰기</button>
<button class="btn btn-secondary" type="button" id="btn-back">돌아가기</button>
</div>
</form>
</div>
</div>
</main>
<footer class="container-fluid mt-5 p-5 border-top">
<p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>
</html>
boardWrite_process.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ include file="dbconn.jsp"%>
<%
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("title");
String userId = request.getParameter("userId");
String contents = request.getParameter("contents");
PreparedStatement pstmt = null;
// INSERT 해줄거라서 rs 필요없음
try {
String sql = "INSERT INTO board (title, contents, user_id, create_date) ";
sql += "VALUES (?, ?, ?, now()) ";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, contents);
pstmt.setString(3, userId);
pstmt.executeUpdate();
}
catch (SQLException e) {
out.println("SQLException : " + e.getMessage());
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
}
// 실행 다 되고나면 첫 페이지로 돌아가게 만들기
response.sendRedirect("boardList.jsp");
%>