谁帮我看下,为什么下面代码无法rollback??
package com.hwz.dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HwzTest {
public static void main(String[] args) throws SQLException{
   Statement st=null;
   ResultSet rs=null;
   Connection conn=null;
   Conn co=new Conn();
   try{
   conn=Conn.getConn();
   conn.setAutoCommit(false);
   st=co.getSt();
   String sql=null;
   int age=0;
   sql="update classname set age=age-1 where id=3";
   st.executeUpdate(sql);
   sql="select * from classname where id=4";
   rs=st.executeQuery(sql);
   if(rs.next()){
  age=rs.getInt(3); 
   }
   if(age>1)
   throw new RuntimeException("年龄太大");
   sql="update classname set age=age+1 where id=4";
   st.executeUpdate(sql);
   conn.commit();
   }catch(SQLException e){
   if(conn!=null){
   conn.rollback();
   throw e;
   }
   }finally{
     co.getClose();
   }
}
}
是哪边写错了吗??

解决方案 »

  1.   

       在异常处理catch块中,只要conn!=null就回滚,因此在try块中,代码只执行到conn=Conn.getConn();这一步就直接跳到catch块中去回滚,而在try块中的conn=Conn.getConn()后面的语句将不会再被执行,这样的话你的一些update、select操作根本就没有被执行,当然不好回滚。
        我想问题应该出在这,你不妨Debug看看。
      

  2.   

    我找到原因了,在事务中我给人家实例化了一个Conn的对象,导致回滚错误.我不实例化就没问题.
    在catch是因为抛了异常才跳,不是得到对象就跳.
      

  3.   

        不好意思,之前我说错了。当try块中发生了SQLException,程序会跳到相应catch块执行异常处理操作,先判断conn!=null(true的话进行回滚)。如果在try块中没有发生SQLException异常,就不会跳到catch块执行那个回滚操作,但是finally块一定会执行的。