背景
jdbc单个库的事务实际上是很简单的,原本觉得没必要写,但是想了想还是写了。
简介
jdbc的事务默认是自动开启的,也就是,每执行一次sql就直接会提交事务,这样的话就会有个问题,当我们要执行多条SQL语句时,如果只有前面几条语句执行成功,但是后面的SQL语却执行失败的话,那么数据库中就会残留执行成功的数据,而执行失败的语句则自然不会有数据残留,但是这却会导致数据不匹配、不完整,这样也就会出错
解决方案
最后统一提交事务,如果有失败的就不提交,直接回滚。
- connection.setAutoCommit(false);//关闭自动提交
- connection.commit();//手动提交
- connection.rollback();//异常,回滚
import java.sql.*;
public class JDBC11 {
public static void main(String[] args){
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yhsql","root","root");
connection.setAutoCommit(false);
String sql1 = "insert into dept (deptno,dname,loc) values (?,?,?)";
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.setInt(1,99);
preparedStatement.setString(2,"狗日");
preparedStatement.setString(3,"阿萨德");
int i = preparedStatement.executeUpdate();
System.out.println(i == 1 ? "添加数据成功":"添加数据失败");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String sql2 = "delete from dept where deptno = ?";
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.setInt(1,60);
i += preparedStatement.executeUpdate();
System.out.println(i == 2 ? "删除数据成功":"删除数据失败");
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String sql3 = "update dept set deptno = 60 where deptno = ?";
preparedStatement = connection.prepareStatement(sql3);
preparedStatement.setInt(1,99);
i += preparedStatement.executeUpdate();
System.out.println(i == 3 ? "更新数据成功":"更新数据失败");
System.out.printf("事务全部执行完毕,开始提交...已提交");
connection.commit();
} catch (Exception e) {
e.printStackTrace();
if ( connection != null){
try{
connection.rollback();
} catch (SQLException e2) {
e2.printStackTrace();
}
}
}
finally{
try{
if ( connection!=null)
connection.close();
}
catch(SQLException e){
e.printStackTrace();
}
try {
if ( preparedStatement!=null)
preparedStatement.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
|