1. JDBC에서 트랜잭션 처리

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import = "java.sql.DriverManager" %>    
<%@ page import = "java.sql.Connection" %>   
<%@ page import = "java.sql.PreparedStatement" %>   
<%@ page import = "java.sql.ResultSet" %>   
<%@ page import = "java.sql.SQLException" %>  
<%
	String idValue = request.getParameter("id");

	Connection conn = null;
	PreparedStatement pstmtItem = null;
	PreparedStatement pstmtDetail = null;
	
	String jdbcDriver= "jdbc:mysql://localhost:3306/chap14?" +
						"useUnicode=true&characterEncoding=utf8";
	String dbUser = "jspexam";
	String dbPass = "jsppw";
	
	Throwable occuredException = null;
	
	try {
		int id = Integer.parseInt(idValue);
		
		conn = DriverManager.getConnection(jdbcDriver, dbUser, dbPass);
		conn.setAutoCommit(false); //트랜잭션 시작
		
        	//첫 번째 쿼리
		pstmtItem = conn.prepareStatement("insert into ITEM values(?, ?)");
		pstmtItem.setInt(1, id);
		pstmtItem.setString(2, "상품 이름" + id);
		pstmtItem.executeUpdate();
		
		if(request.getParameter("error") != null) {
			throw new Exception("의도적 익셉션 발생");
		}
		
       		//두 번째 쿼리
		pstmtDetail = conn.prepareStatement(
				"insert into ITEM_DETAIL values(?, ?)");
		pstmtDetail.setInt(1, id);
		pstmtDetail.setString(2, "상세 설명: " + id);
		pstmtDetail.executeUpdate();
		
		conn.commit(); 				//트랜잭션 커밋
	} catch(Throwable e) {
		if(conn != null) {
			try {
				conn.rollback();	//트랜잭션 커밋 되지 않으면 롤백됨
			} catch(SQLException ex) {}
		}
		occuredException = e;
	} finally {
		if(pstmtItem != null)
			try { pstmtItem.close(); } catch(SQLException ex) {}
		if(pstmtDetail != null)
			try { pstmtDetail.close(); } catch(SQLException ex) {}
	}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ITEM 값 입력</title>
</head>
<body>
<% if(occuredException != null) { %>
에러가 발생하였습니다 : <%= occuredException.getMessage() %>
<% } else { %>
데이터가 성공적으로 들어감
<% } %>
</body>
</html>

- 파라미터 지정 전

- id 파라미터 지정 후

- error 파라미터 값 지정

→ 첫 번째 쿼리 실행 후 error 파라미터 값이 null이 아니면(즉, error가 존재하면) 익셉션을 발생시켜서 두 번째 쿼리를 실행하지 않음

→ 첫 번째 쿼리 시작 전 트랜잭션을 시작하기 때문에 error 파라미터가 존재할 경우 첫 번째 쿼리 실행 결과가 DB에 반영되지 않고 롤백됨

+ Recent posts