jdbc设置手动提交事务后还有必要考虑回滚吗?只要执行不到commit()方法之前就算有异常那也不会提交事务啊,对数据也没有影响啊。
18行到39行
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Test {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedstatement = null;
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
String url = "jdbc:mysql:/";
String username = "";
String password = "";
connection = DriverManager.getConnection(url,username,password);
connection.setAutoCommit(false);//手动提交
//3.获取数据库操作对象
preparedstatement = connection.prepareStatement("update account set balance = ? where id = ?");
//传值
preparedstatement.setInt(1,5000);
preparedstatement.setString(2,"zhang");
//4.执行sql
preparedstatement.executeUpdate();
String s = null;//模拟中途出现异常,后面语句无法执行
s.toString();
//传值
preparedstatement.setInt(1,5000);
preparedstatement.setString(2,"li");
//4.执行sql
preparedstatement.executeUpdate();
connection.commit();//手动提交
} catch (Exception throwables) {
//捕获到异常回滚事务
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
//6.释放资源
if (preparedstatement != null) {
try {
preparedstatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
你的理解是对的。在异常捕获中处理回滚即可。没有执行到commit方法不会提交数据的。望采纳!!
即使设置了手动提交事务,也有必要考虑回滚。因为在手动提交事务的情况下,如果在未执行commit()的情况下发生了异常,那么事务就会回滚到开始的状态。回滚可以保证数据的一致性,防止数据损坏或无效状态。如果不考虑回滚,当发生异常时,虽然数据没有提交,但数据库中可能已经存在部分修改。如果下一次操作需要依赖之前的操作,就可能会出现问题。因此,建议在手动提交事务时,始终考虑回滚操作。
没提交的事务也是占用数据库资源的,每个事务都有独立的可见数据范围记录。
不提交事务,占用的connection也不会及时释放,如果线程池被占满了,系统就炸了。