问题描述:代码没有报错,且在用来测试的 /by zero 异常处能够成功捕获异常,而后也成功执行了rollback()操作,但数据库并未成功回滚,已做的SQL语句操作都被执行了。
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
conn = JDBCUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
//SQL语句
String sql = "update band set name = ? where id < 14";
String sql2 = "update band set name = ? where id >= 14";
//预编译
pstmt1 = conn.prepareStatement(sql);
pstmt2 = conn.prepareStatement(sql2);
//赋值
pstmt1.setString(1,"软工");
pstmt2.setString(1,"计科");
//执行语句1
pstmt1.executeUpdate();
//手动制造异常!
int a = 3/0;
pstmt2.executeUpdate();
// 如果执行到这里还没有问题,则提交事务
conn.commit();
} catch (Exception e) {
e.printStackTrace();
//发生异常,事务回滚!
try {
if (conn != null) {
conn.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}finally {
JDBCUtils.close(null,pstmt1,conn);
JDBCUtils.close(null,pstmt2,null);
}
}
原因:如下图,MySQL默认的存储引擎是MyISAM,而MylSAM不支持事务,因此开关事务的操作是无效的。
那么只要给表换个支持事务的引擎(图上的innoDB)就可以了
ALTER TABLE band ENGINE = InnoDB;