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();
            }
        }
    }
}

作者:hashifei

出处:https://www.cnblogs.com/hashifei/p/18179399

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   哈士费  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示