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);
}
}
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);
}
}
conn.rollback();
conn.setAutoCommit(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
换为:
e.printStackTrace();
try {
conn.rollback();
conn.setAutoCommit(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
看看异常的信息吧。
String sql = "insert into student values(?, ?, ?)";
换成:
String sql = "insert into student(id,name,age) values(?, ?, ?)";
楼主知道conn.setAutoCommit(true);
是什么意思吗?楼主把conn.setAutoCommit(true);
全部去掉。如果要有程序控制事物,必须是conn.setAutoCommit(false);而且程序必须调用commit或者rollback方法。因此,只需在开始写一次conn.setAutoCommit(false)就可以