今天在测试JDBC事务的时候,发现事务回滚没用
这是我写的代码:
package Test;
import utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestTransaction {
public static void main(String[] args){
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
String sql1 = "update account set money = money - 100 where id = 1";
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
int i = 1 / 0;
String sql2 = "update account set money = money + 100 where id = 2";
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();
System.out.println("commit");
connection.commit();
}catch (Exception e){
System.out.println("rollback");
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}finally {
DBUtil.closeConnection(connection, preparedStatement, null);
}
}
}
加了int i = 1 / 0之后,每次都是第一条成功,第二条失败,但显示rollback执行了
解决方法:
- 检查你的
connection.setAutoCommit(false);
是否写了,如果写了还没用看下一条 - sql命令行执行
show table status from 数据库名;
看看是不是你的表是MyISAM的,如果是则执行ALTER TABLE 表名ENGINE = InnoDB;
就可以完美解决了!!!
最新回复