JDBC 回滚 rollback

package com.gemonno.JDBC;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;


public class TserRollBack {
Connection coon ;
PreparedStatement pstm;
ResultSet rs;
Savepoint sp = null;//设置回滚点
public static void main(String[] args) throws SQLException {
TserRollBack trb = new TserRollBack();
trb.update();

}


public void update() throws SQLException {
try {

coon = JDBCUtil.getInstance().getConnection();
coon.setAutoCommit(false);//设置为false;事物不会自动提交;
String sql =" update emp set salaty =5000 where eno =105  ";
pstm =coon.prepareStatement(sql);
pstm.executeUpdate();

sp = coon.setSavepoint();//在这里设置回滚点;只回滚到这里,就可以让上面的语句执行完,不必回滚;



sql ="select salaty from emp ";
pstm =coon.prepareStatement(sql);
rs =pstm.executeQuery();
rs.next();
double d  =rs.getDouble(1);
System.out.println(d);

if(d>4000) {
throw new RuntimeException("da yu 4000");//这里抛异常,要在下面捕获异常;
}
if (d<=4000) {

sql = "update emp set salaty =6000  where eno =107 ";
pstm=coon.prepareStatement(sql);
pstm.executeUpdate();
}
coon.commit();//事物在这里才提交;
}catch(RuntimeException e) {
if (coon!=null&&sp!=null) {

coon.rollback(sp);//当catch到上面d》4000的异常时候,就会执行这里的语句。回滚到设置的回滚点

                                coon.commit();//回滚之后也要提交;

}

catch (SQLException e) {
if (coon!=null) {

coon.rollback();//上面的语句虽然 在false的情况下未提交但是已经执行,要回滚到原来的状态;

                                  

throw e;//这里要抛异常,方法上也要抛,要让调用他的人看到异常的情况;
}
}finally {
JDBCUtil.getInstance().release(pstm, rs, coon);
}

}
}

你可能感兴趣的:(java,测试)