Transaction 을 적용하지 않은 경우
import java.sql.*;
/* emp 테이블의 SAL컬럼을 은행의 계좌 잔고로 가정하고
* WARD가 200을 SMITH에게 송금한 직후에 에러가 발생하는 경우를 예로 들었다.
* 그룹단위 트랜잭션을 적용하지 않은 상태의 코드이므로 WARD는
* 송금하여 잔고가 줄었으나, SMITH는 송금을 받지 못하여 잔고가
* 변함이 없다. 송금했지만 받지 못하는 상황이 된다.
*/
class Transaction01 {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e){e.printStackTrace();}
String dbURL = "jdbc:oracle:thin:@localhost:1521:ORCL";
Connection con = null;
PreparedStatement pstmt = null;
boolean b = true;
try{
con = DriverManager.getConnection(dbURL, "scott", "tiger");
pstmt = con.prepareStatement("update emp set sal=? where ename=?");
pstmt.setInt(1, 800);//200을 SMITH한테 송금하므로 -200해서 잔고 800으로 변경
pstmt.setString(2, "WARD");
pstmt.executeUpdate();
System.out.println("WARD가 송금했음");
if(b) throw new Exception("처리도중 에러!");
pstmt.setInt(1, 1200);//200을 받았기 때문에 기존 1000에 200을 더해 수정
pstmt.setString(2, "SMITH");
pstmt.executeUpdate();
System.out.println("SMITH가 받았음");
}catch(Exception e){
try{
System.err.println("실행 중에 오류 발생");
}catch(Exception se){se.printStackTrace();}
}finally{
try{
if(pstmt!=null)pstmt.close();
if(con!=null)con.close();
}catch(Exception e) {e.printStackTrace();}
}
}
}