JDBC操作事务

 首先我们先用IDEA连接数据库

IDEA连接数据库

 

 

 连接成功后可以选择数据库:

 双击数据库,可进行一些操作

 模拟转账成功:

public class TestTransaction1 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs= null;
        try {
            conn = JdbcUtils.getConnection();
            //关闭数据库自动提交,自动会开启事务
            conn.setAutoCommit(false);
            String sql1 = "update account set money = money-100 where name='A'";
            pst=conn.prepareStatement(sql1);
            pst.executeUpdate();
            String sql2 = "update account set money = money+100 where name='B'";
            conn.prepareStatement(sql2);
            pst.executeUpdate();
            //提交事务
            conn.commit();
            System.out.println("成功!");
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,pst,rs);
        }
    }
}

模拟转账失败:

public class TestTransaction2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs= null;
        try {
            conn = JdbcUtils.getConnection();
            //关闭数据库自动提交,自动会开启事务
            conn.setAutoCommit(false);
            String sql1 = "update account set money = money-100 where name='A'";
            pst=conn.prepareStatement(sql1);
            pst.executeUpdate();
            int x =1/0;//报错
            String sql2 = "update account set money = money+100 where name='B'";
            conn.prepareStatement(sql2);
            pst.executeUpdate();
            //提交事务
            conn.commit();
            System.out.println("成功!");
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,pst,rs);
        }
    }
}

 

posted on 2022-12-21 09:55  键盘敲烂的朱  阅读(20)  评论(0编辑  收藏  举报