JDBC MySQL开启事务

2021/8/2 19:09:50

本文主要是介绍JDBC MySQL开启事务,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

通过控制事务,达到数据更新的一致性

    @Test
    public void test01(){
        //事务
        /*
        connection.setAutocommit(false);
        connection.rolLback( );//回滚
        connection.lommit();//提交

         */
        String url="jdbc:mysql://localhost:3306/kanfang";
        String user = "root";
        String password="123456";
        Connection connection=null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            //开启事务
            connection.setAutoCommit(false);
            String sql1="update account set balance=balance-500 where sname = '李白'";
            String sql2="update account set balance=balance+500 where sname = '杜甫'";
            PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
            PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
            preparedStatement1.executeUpdate();
            preparedStatement2.executeUpdate();
            //提交事务
            connection.commit();
            System.out.println("转账成功!");

        } catch (SQLException throwables) {
            try {
                //事务回滚
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }finally {
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }



这篇关于JDBC MySQL开启事务的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程