JSP, Servlet, MySQL/JSP - webmarket
JSP Servlet JDBC로 데이터베이스와 JSP 연동 : 상품 조회, 등록, 수정, 삭제하기 5
샤리미
2024. 3. 7. 23:36
728x90
반응형
데이터베이스에 저장된 상품 삭제하기
-상품 편집 페이지 작성하기
WebMarket/Webcontent/editProduct.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- 폼 페이지에 입력 항목의 데이터를 검사하는 핸들러 함수가 저장된 바바스크립트 파일 validation.js를 가져오도록 작성 -->
<title>상품 편집</title>
<script type="text/javascript">
function deleteConfirm(id){//자바스크립트로 상품 삭제 여부를 확인하는 핸들러 함수 deleteConfirn() 을 작성한다.
if(confirm("해당 상품을 삭제합니다!!") == true)
location.href = "./deleteProduct.jsp?id=" + id;
else
return;
}
</script>
<%
//요청 파라미터 edit 값을 전달받도록 request 내장 객체의 getParameter() 메소드를 작성한다.
String edit = request.getParameter("edit");
%>
</head>
<body>
<jsp:include page="menu.jsp"/>
<div class="jumbotron">
<div class="container">
<h1 class="display-3">상품 편집</h1>
</div>
</div>
<div class="container">
<div class="row" align="center">
<%@ include file="dbconn.jsp" %>
<%
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "select * from product";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()){
%>
<div class="col-md-4">
<img src="${pageContext.request.contextPath}/resources/images/<%=rs.getString("p_fileName") %>" style="width:100%">
<h3><%=rs.getString("p_name") %></h3>
<p><%=rs.getString("p_description") %>
<p><%=rs.getString("p_UnitPrice") %>원
<p><%
if(edit.equals("update")){
%>
<a href="./updateProduct.jsp?id=<%=rs.getString("p_id") %>" class="btn btn-success" role="button">수정 »</a>
<%
} else if (edit.equals("delete")) {
%>
<!-- <삭제> 버튼을 클릭하면 핸들러 함수 deleteConfirn() 이 실행되도록 onclick 속성을 작성한다. -->
<a href="#" onclick="deleteConfirm('<%=rs.getString("p_id")%>')" class="btn btn-danger" role="button">삭제 »</a>
<%
}
%>
</div>
<%
}
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
%>
</div>
<hr>
</div>
<jsp:include page="footer.jsp"/>
</body>
</html>
-상품 삭제 페이지 작성하기
WebMarket/Webcontent/deleteProduct.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.sql.*" %>
<%@ include file = "dbconn.jsp" %>
<%@ page errorPage="exceptionNoProductId.jsp" %>
<%
//자체로 추가함.. 오류때매
PreparedStatement pstmt = null;
ResultSet rs = null;
String productId = request.getParameter("id");
String sql = "select * from product";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()){
sql = "delete from product where p_id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, productId);
pstmt.executeUpdate();
} else
out.println(" 일치하는 상품이 없습니다. ");
if(rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
response.sendRedirect("editProduct.jsp?edit=delete");
%>
<!--
String productId = request.getParameter("id");
String sql = "select * from product";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if(rs.next()){
sql = "delete from product where p_id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, productId);
pstmt.executeUpdate();
} else
out.println("일치하는 상품이 없습니다.");
if (rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
response.sendRedirect("editProduct.jsp?edit=delete");
-->
JDBC 로 데이터베이스와 JSP 연동 [ 요약 ]
01 JDBC 의 개요
- JDBC 는 자바 /JSP 프로그램 내에서 데이터베이스와 관련된 작업을 처리할 수 있도록 도와주는 자바 표준 인터페이스로, 관계형 데이터베이스 시스템에 접근하여 SQL 문을 실행하기 위한 자바 API 또는 자바 라이브러리 이다.
02 JDBC 드라이버 로딩 및 DBMS 접속
- JDBC 드라이버 로딩 단계에서는 드라이버 인터페이스를 구현하는 작업으로 Class.forName() 메소드를 이용하여 JDBC 드라이버를 로딩한다. JDBC 드라이버가 로딩되면 자동으로 객체가 생성되고 DriverManager 클래스에 등록된다.
- JDBC 드라이버에서 데이터베이스와 연결된 커넥션을 가져오기 위해 DriverManager 클래스의 getConnection() 메소드를 사용한다.
- 데이터베이스 연결이 더이상 필요하지 않으면 데이터베이스와 JDBC 리소스가 자동으로 닫힐떄까지 대기하는 것이 아니라 close() 메소드로 Connection 객체를 해제한다.
03 데이터베이스 쿼리 실행
Statement 객체는 정적인 쿼리에 사용한다.
- executeQuery() 메소드는 정적인 SELECT 쿼리문을 통해 데이터를 검색하는 데 사용한다.
- executeUpdate() 메소드는 INSERT, UPDATE, SELECT 쿼리문을 통해 데이터를 삽입, 수정, 삭제하는 데 사용한다.
PreparedStatement 객체는 동적인 쿼리에 사용한다.
- executeQuery() 메소드는 동적인 SELECT 쿼리문을 통해 데이터를 검색하는데 사용한다.
- executeUpdate() 메소드는 INSERT, UPDATE, SELECT 쿼리문을 통해 데이터를 삽입, 수정 ,삭제하는데 사용한다.
04 쿼리문 실행 결과 값 가져오기
SELECT 쿼리문의 실행 결과 값을 가져오는 ResultSet 객체의 형식은 다음과 같다.
- Statement 객체를 사용하는 경우
ResultSet executeQuery(String sql) throws SQLException
- PreparedStatement 객체를 사용하는 경우
ResultSet executeQuery() throws SQLException
728x90
반응형