日期:2014-05-20 浏览次数:21200 次
public void addStudent(List<Student> students) { Connection conn = DB.getConnection(); String sql = "insert into student values(?, ?, ?)"; PreparedStatement pstmt = null; try { pstmt = conn.prepareStatement(sql); conn.setAutoCommit(false); for(int i=0; i<students.size(); i++) { Student s = students.get(i); pstmt.setInt(1, s.getId()); pstmt.setString(2, s.getName()); pstmt.setInt(3, s.getAge()); pstmt.addBatch(); } pstmt.executeBatch();// 在此卡住,没有出现异常,但就是不动 conn.commit(); conn.setAutoCommit(true); } catch (SQLException e) { try { conn.rollback(); conn.setAutoCommit(true); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { DB.close(pstmt); DB.close(conn); } }
String sql = "insert into student values(?, ?, ?)";
------解决方案--------------------
怎么写了这么多的conn.setAutoCommit(true);
楼主知道conn.setAutoCommit(true);
是什么意思吗?楼主把conn.setAutoCommit(true);
全部去掉。如果要有程序控制事物,必须是conn.setAutoCommit(false);而且程序必须调用commit或者rollback方法。因此,只需在开始写一次conn.setAutoCommit(false)就可以