JDBC管理事务

1.JDBC事务管理

connection类来管理事务

setAutoCommit(boolean boo)-如果boo为true自动提交事务 如果boo是false为开启事务
commit()-手动提交事务
rollBack()-回滚事务

2.手搓代码

        public static void main(String[]args) throws Exception {
            Scanner scr=new Scanner(System.in);
            //记住此代码你要更改url user password 这三个参数 
            //用connection进行事务管理
            //注册驱动
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            //Class.forName("com.mysql.jdbc.Driver");
            //获取连接
            String url="jdbc:mysql://127.0.0.1:3306/数据库?useSSL=false";/*jdbc:mysql://ip地址:端口信息/连接那个数据库?参数
            自己的计算机ip是127.0.0.1端口是3306 useSSL=false避免报警告*/
            String user="root";//mysql的用户名
            String password="1234";//mysql的密码
            Connection connection =DriverManager.getConnection(url,user,password);
            //获取执行对象
            Statement statement=connection.createStatement();
            //sql语句
            String sql="update student set sex='男' where id=2";
            String sql1="update student set name='小聪明' where id=2";
            try{
                //开启事务
                connection.setAutoCommit(false);
                //执行sql语句
               statement.executeUpdate(sql);
               statement.executeUpdate(sql1);
                //提交事务
                connection.commit();
                System.out.println("事务完成!!!");
            }catch (Exception e)
            {
                e.printStackTrace();
                connection.rollback();
            }
            //关闭 先开后关 后开先关
            statement.close();
            connection.close();
            scr.close();
        }

总结

如果你想要同时执行多条sql语句(当有至少一条语句不正确就回滚所有事务即都不执行)时,就要用到事务管理。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是赖猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值