事务
前提:要么都成功,要么都失败
ACID 原则
原子性:要么都完成,要么都失败
一致性:最终一致性
隔离性:多个进程互不干扰
持久性:一般提交不可逆,持久化到数九
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复度:在同一个事务内重复读取表中的数据,表数据发生了变化
幻读:在一个事务内,读取到了别人插入的数据,导致前后读取的数据不一致
代码实现
1.开启事务
//关闭数据库的自动提交,会自动开启事务
conn.setAutoCommit(false);
2.一组业务执行完毕,提交事务
3.可以在catch语句中,显示的定义回滚事务,但是默认失败会自动回滚
public class TestTransaction1 {
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 acconut set money = money-100 where name = 'A'";
String sql2 = "update acconut set money = money+100 where name = 'B'";
st = conn.prepareStatement(sql1);
st.executeUpdate();
int x = 1/0;//报错
st = conn.prepareStatement(sql2);
st.executeUpdate();
//业务完毕,称从提交事务
conn.commit();
System.out.println("成功!");
} catch (SQLException throwables) {
// try {
// // 如果失败,则默认回滚
// conn.rollback();//如果失败则回滚事务
// } catch (SQLException e) {
// e.printStackTrace();
// }
} finally {
JdbcUtils.release(conn,st,rs);
}
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接