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();
}
}
}
}
}