package com.itheima.tx; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; import org.junit.Test; import com.itheima.utils.JdbcUtil; /** * 转账 事务控制 * update account set money=money-100 where name='aaa'; update account set money=money+100 where name='bbb'; * @author wangli * * * 开事务 * con.setAutoCommit(false); * * 提交 * con.commit(); * 回滚 * con.rollback(); * */ public class TransactionDemo1 { @Test public void testTransaction(){ Connection con = null; PreparedStatement st =null; PreparedStatement st2 = null; try { con = JdbcUtil.getConnection(); //设置隔离级别,一定是放在开启事务前 con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); con.setAutoCommit(false);// 放在得到st之前 st = con.prepareStatement("update account set money=money-100 where name='aaa'"); st.executeUpdate(); //int i=1/0; st2 = con.prepareStatement("update account set money=money+100 where name='bbb'"); st2.executeUpdate(); con.commit();//提交 } catch (Exception e) { e.printStackTrace(); if(con!=null){ try { con.rollback();//回滚 } catch (SQLException e1) { e1.printStackTrace(); } } }finally{ JdbcUtil.release(null, st, con); } } }