使用JDBC管理事务
1.JDBC控制事务
-
事务:一个包含多个步骤的业务操作,如果业务操作被事务管理,则这个多个步骤要么同时成功,要么同时失败
-
操作
- 开启事务
- 提交事务
- 回滚事务
-
使用Connection对象来管理事务
开启事务:setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即开启事务
在执行Sql语句之前开启事务
提交事务:void commit()
当所有Sql都成功执行完成后提交事务
回滚事务:void rollback()
在catch中回滚事务
/*
* jdbc处理事务的处理
* */
public class JdbcWord {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
//1.导入Jar包
//2.注册驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//获得数据库连接对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user4", "root", "root");
connection.setAutoCommit(false); //开启事务
//定义Sql语句
String sql1 ="update account set balance=?where id=?";
String sql2 ="update account set balance=?where id=?";
//获得执行Sql的对象
preparedStatement1 = connection.prepareStatement(sql1);
preparedStatement2 = connection.prepareStatement(sql2);
//给占位符赋值
preparedStatement1.setDouble(1,19999);
preparedStatement1.setInt(2,1);
//int sun = 3/0; //制造异常
preparedStatement2.setDouble(1,168168);
preparedStatement2.setInt(2,1);
//执行Sql语句
int i = preparedStatement1.executeUpdate();
int i1 = preparedStatement2.executeUpdate();
//处理结果
System.out.println(i);
System.out.println(i1);
//提交事务
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}
finally {
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement1!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement2!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}