Loading

10.JDBC事务

要么都成功,要么都失败!
ACID原则:保证数据的安全。

开启事务
事务提交
事务回滚
关闭事务

转账:
A:1000
B:1000

A(900)--100-->B(1100)
public class TestJDBC2 {
    @Test
    public void test() {

        // 配置信息
        String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        Connection connection = null;
        // 1.加载驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 2.连接数据库 代表数据库
            connection = DriverManager.getConnection(url, username, password);
            // 3.通知数据库开启事务
            connection.setAutoCommit(false); //false是开启
            String sql = "update account set money = money-100 where name = 'A'";
            connection.prepareStatement(sql).executeUpdate();

            //制造错误
            int i = 1/0;
            String sql2 = "update account set money = money+100 where name = 'B'";
            connection.prepareStatement(sql2).executeUpdate();

            connection.commit();
            System.out.println("提交成功");
        }catch (Exception e){
            try {
                //如果出现异常 就通知数据库回滚事务
                if (connection != null) {
                    connection.rollback();
                }
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            try {
                connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
posted @ 2024-05-08 12:04  哈士费  阅读(20)  评论(0)    收藏  举报