事务
ACID原则
原子性:要么都完成,要么都不完成
一致性:总数不变
隔离性:多个业务互不干扰
持久性:一旦提交不可逆, 持久化到数据库
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复度:在同一个事务内,重复读取表中的数据,表数据发生了变化
虚度(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来结果不一致
代码实现:
import com.qsy.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();
//int x =1/0; //报错尝试
String sql2 = "UPDATE account set money = money+100 WHERE name = ‘B‘";
st = conn.prepareStatement(sql2);
st.executeUpdate();
//业务完毕,提交事务
conn.commit();
System.out.println("操作成功");
} catch (SQLException e) {
//不写也会回滚
// try {
// conn.rollback();//如果失败则回滚事务
// } catch (SQLException e1) {
// e1.printStackTrace();
// }
e.printStackTrace();
}finally {
JdbcUtils.release(conn,st,rs);
}
}
}
工具类代码:
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static{
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1.驱动只用加载一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//释放连接资源
public static void release(Connection conn, Statement st, ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}