JDBC管理事务

使用JDBC管理事务

1.JDBC控制事务

  1. 事务:一个包含多个步骤的业务操作,如果业务操作被事务管理,则这个多个步骤要么同时成功,要么同时失败

  2. 操作

    1. 开启事务
    2. 提交事务
    3. 回滚事务
  3. 使用Connection对象来管理事务

    ​ 开启事务:setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即开启事务

    ​ 在执行Sql语句之前开启事务

    ​ 提交事务:void commit()

    ​ 当所有Sql都成功执行完成后提交事务

    ​ 回滚事务:void rollback()

    ​ 在catch中回滚事务

/*
* jdbc处理事务的处理
* */
public class JdbcWord {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        //1.导入Jar包
        //2.注册驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //获得数据库连接对象
           connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user4", "root", "root");
           connection.setAutoCommit(false); //开启事务
            //定义Sql语句
            String sql1 ="update account set balance=?where id=?";
            String sql2 ="update account set balance=?where id=?";

            //获得执行Sql的对象
            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement2 = connection.prepareStatement(sql2);

            //给占位符赋值
            preparedStatement1.setDouble(1,19999);
            preparedStatement1.setInt(2,1);
            //int sun = 3/0; //制造异常
            preparedStatement2.setDouble(1,168168);
            preparedStatement2.setInt(2,1);

            //执行Sql语句
            int i = preparedStatement1.executeUpdate();
            int i1 = preparedStatement2.executeUpdate();

            //处理结果
            System.out.println(i);
            System.out.println(i1);

            //提交事务
            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {

            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (preparedStatement1!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if (preparedStatement2!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值