/**
* 事务四个特性:
* 1.原子性
* 2.一致性
* 3.隔离性
* 4.持续性
* @author John
*
*/
public class TransactionDemo {
@Test
public void transaction1() throws SQLException{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
JDBCUtils utils = JDBCUtils.getInstance();
String sql1 = "update user set age=age-1 where id = 6";
String sql2 = "select age from user where id = 7";
try {
conn = utils.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement(sql1);
ps.executeUpdate();
ps = conn.prepareStatement(sql2);
rs = ps.executeQuery();
while(rs.next()){
int age = rs.getInt("age");
if(age>11){
throw new RuntimeException("大于11");
}
}
conn.commit();
} catch (SQLException e) {
if(conn!=null){
conn.rollback();
}
throw e;
}finally{
utils.free(conn, ps, rs);
}
}
@Test
public void savePoint1() throws SQLException{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
JDBCUtils utils = JDBCUtils.getInstance();
String sql1 = "update user set age=age-1 where id = 6";
String sql2 = "select age from user where id = 7";
String sql3 = "update user set age=age-1 where id = 5";
Savepoint sp=null;
try {
conn = utils.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement(sql1);
ps.executeUpdate();
sp=conn.setSavepoint();
ps = conn.prepareStatement(sql3);
ps.executeUpdate();
ps = conn.prepareStatement(sql2);
rs = ps.executeQuery();
while(rs.next()){
int age = rs.getInt("age");
if(age>11){
throw new RuntimeException("不得大于11");
}
}
conn.commit();
} catch (RuntimeException e) {
if(conn!=null && sp!=null){
conn.rollback(sp);
conn.commit();
}
throw e;
}finally{
utils.free(conn, ps, rs);
}
}
}