zoukankan      html  css  js  c++  java
  • Jdbc事务

    事务模拟转账

    A向B转账100元,基于事务的ACID原则,前后的总钱数必须一致,简单的sql语句如下,而且两个语句一起执行才能完成转账这一事务,否则金额会出错。

    update account set money= money-100 where name='A'
    
    update account set money= money+100 where name='B'
    

    代码实现

    public class TestTransation {
        private static Connection connection=null;
        private static PreparedStatement statement=null;
        private static ResultSet resultSet=null;
    
        public static void main(String[] args) throws SQLException {
            try {
                connection= JDBCutil.getConnection(); //JDBCutil为个人编写的数据库连接工具类
                //关闭数据库的自动提交,自动会开启事务
                connection.setAutoCommit(false);
    
                String sql1="update account set money= money-100 where name='A'";
                statement= connection.prepareStatement(sql1);
                statement.executeUpdate();
    
                String sql2="update account set money= money+100 where name='B'";
                statement= connection.prepareStatement(sql2);
                statement.executeUpdate();
                connection.commit();
                System.out.println("成功");
            } catch (SQLException throwable) {
                try {
                    connection.rollback();   //失败回滚事务
                    System.out.println("失败");
                } catch (SQLException throwable1) {
                    throwable1.printStackTrace();
                }
            } finally {
                JDBCutil.release(resultSet,statement,connection);
            }
    
        }
    }
    
    

    执行前:

    image-20210205150103117

    执行后:

    image-20210205150203469

  • 相关阅读:
    [SCOI2003]严格N元树
    CF280 C. Game on Tree
    [HDU2281]Square Number
    [HDU5391]Zball in Tina Town
    [HDU3988]Harry Potter and the Hide Story
    [HDU5794]A Simple Chess
    [HDU5451]Best Solver
    [HDU1724]Ellipse
    [HDU6304]Chiaki Sequence Revisited
    [HDU6343]Graph Theory Homework
  • 原文地址:https://www.cnblogs.com/xiaxiaopi/p/14377817.html
Copyright © 2011-2022 走看看