有些场景需要用到事务的操作,比如转账的流程,需要同时成功才行。
package cn.JdbcUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /* * 事务处理 * 转账为例,张三转给李四500 * 制造一个异常 */ public class JdbcTest6 { public static void main(String[] args) { Connection con = null; PreparedStatement prep1 = null; PreparedStatement prep2 = null; // 获取数据库连接 try { //1.数据库连接 con = DriverManager.getConnection("jdbc:mysql:///test", "root", "newpassword"); //开启事务 con.setAutoCommit(false); //2.定义sql //2.1张三 - 500 String sql1 = "update money set salary = salary - ? where id = ?"; //2.2李四 +500 String sql2 = "update money set salary = salary + ? where id = ?"; //3.获取sql执行对象 prep1 = con.prepareStatement(sql1); prep2 = con.prepareStatement(sql2); //4.设置参数 prep1.setDouble(1, 500.00); prep1.setInt(2, 1); prep2.setDouble(1, 500.00); prep2.setInt(2, 2); //5.执行sql prep1.executeUpdate(); //制造一个异常 int x = 3/0; prep2.executeUpdate(); //运行到最后提交事务 con.commit(); } catch (Exception throwables) { //有异常则进行回滚 try { //判断con不为null才进行回滚 if(con != null){ con.rollback(); } } catch (SQLException e) { e.printStackTrace(); } throwables.printStackTrace(); } finally { if (prep1 != null) { try { prep1.close(); prep2.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } if (con != null) { try { con.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } } }
可以尝试去掉事务运行则发生异常,张三痛失500块,而李四没收到钱。
加上事务后运行,即使发生了异常也不会掉钱。
去掉异常,转账成功。