事务
要么都成功,要么都失败
ACID原则
原子性:要么全部完成,要么都不完成
一致性:总数不变
隔离性:多个进程互不干扰
持久性:一旦提交不可逆,持久化到数据库了
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复读:在同一个事务内,重复读取表中的数据,表数据发生了改变
虚读(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来结果不一致
1、开启事务conn.setAutoCommit(false);
2、一组业务执行完毕,提交事务
3、可以在catch语句中显示的定义回滚语句,但默认失败就会回滚
package com.hua.lesson04; import com.hua.lesson02.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestTransaction { public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); //关闭数据库的自动提交,自动会提交事务 conn.setAutoCommit(false);//开启事务 String sql1 = "update account set money = money -100 where name ='A'"; st = conn.prepareStatement(sql1); st.executeUpdate(sql1); String sql2 = "update account set money = money +100 where name ='B'"; st = conn.prepareStatement(sql2); st.executeUpdate(sql2); //业务完毕,提交事务 conn.commit(); System.out.println("成功!"); } catch (SQLException throwables) { //如果失败,则默认回滚 // try { // conn.rollback();//如果失败则回滚事务 // } catch (SQLException e) { // e.printStackTrace(); // } throwables.printStackTrace(); }finally { JdbcUtils.release(conn,st,rs); } } }
我的一生
第1章-废物的一生
第50章-糟糕的婴儿
第300章-莫欺少年穷
第600章-莫欺中年穷
第1000章-莫欺老年穷
第1100章-不详的离去
第1101章-棺材板的震动
第1150章-盗墓贼的眼泪
第1200章-死者为大