日期:2014-05-20  浏览次数:20805 次

JDBC默认在什么时候提交?
PreparedStatement stmtDelete = null;
PreparedStatement stmt = null;

try {
  stmtDelete = conn.prepareStatement(DETAIL_DELETE);
  stmtDelete.executeUpdate();
} catch (SQLException e1) {
  e1.printStackTrace();
}
for (int i = 0; i < rowCount; i++) {
  try {
  stmt = conn.prepareStatement(SQL_INSERT); stmt.executeUpdate();
  System.out.println("inserted Yes!");
  } catch (SQLException e) {
  throw new DataAccessException(e.getMessage(), e);
  } finally {
  try {
  if (stmt != null) {
  stmt.close();
  }
  }
  }
}

//////////////////////////////////////
stmtDelete是删除,stmt是插入
执行stmt时出错了,stmtDelete的语句也没有提交
默认是自动提交的,它是在什么时候提交的?


/////////////////////////////////////
再加个
for(int i=0;;i++){
  List list=new ArrayList();
  list.add(new String("abc"));
  list=null;
}
这个循环会不会内存泄露?

------解决方案--------------------
建议在执行插入和删除时候吧Connection对象设置成手动提交,以便出现异常时候回滚
conn.setAutoCommit(false),比如:
Java code

public void insertUser(User user) {
        
        Connection conn=null;
        try
        {
            conn=JdbcUtil.getConnection();
            conn.setAutoCommit(false);
            PreparedStatement ps=conn.prepareStatement("insert into user(username,fullname,password)values(?,?,?)");
            ps.setString(1, user.getUserName());
            ps.setString(2, user.getFullName());
            ps.setString(3, user.getPwd());
            
            ps.executeUpdate();
            conn.commit();
        }
        catch(SQLException e)
        {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        catch(Exception e)
        {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        finally
        {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

------解决方案--------------------
建议conn.setAutoCommit(false),然后手动提交
如果不这样,系统自动提交
stmtDelete = conn.prepareStatement(DETAIL_DELETE); 
提交一次
stmtDelete.executeUpdate(); 
又提交一次


for(int i=0;;i++){ 
List list=new ArrayList(); 
list.add(new String("abc")); 
list=null; 
}
不会内存泄露
是个死循环,JAVA垃圾回收器会进行垃圾回收,但是这是在系统内存耗量过大或者式没有足够内存
分配时才会调用垃圾回收,这个语句会造成大量垃圾











------解决方案--------------------
insert,update,delete三种是在executeUpdate()或execute()返回时

select是在Result对象中所有行都读取完毕,或用一个Statement对象在同一个连接上执行新的sql命令时

------解决方案--------------------
如果到执行插入的语句才出错,删除语句应该是执行了的,数据库的数据没改变的话你检查下你的sql语句什么的,这种操作应该是放到一个事物里面做的啊。