转账演示事务

package com.bjpowernode.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author:杨青
 * @Time:2021/10/26 19:24
 * @Description:
 *      1.sql脚本:
 *          drop table if exists t_act;
 *          create table t_act(
 *              actno   int,
 *              balance double(7,2)
 *          );
 *          insert into t_act (actno,balance) values(111,20000);
 *          insert into t_act (actno,balance) values(222,0);
 *          select *from t_act;
 *      2.重点三行代码:
 *          conn.setAutoCommit(false);  //开启事务
 *          conn.commit();              //提交事务(事务结束)
 *          conn.rollback();            //回滚事务(事务结束)
 */
public class JDBCTest11 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement ps=null;
        try {
            //1.类加载完成注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode?useSSL=false","root","123456");
            //将自动提交机制修改为手动提交
            conn.setAutoCommit(false);  //开启事务
            //3.获取预编译数据库操作对象
            String sql="update t_act set balance=? where actno=?";
            ps=conn.prepareStatement(sql);
           //给占位符传值
            ps.setDouble(1,10000);
            ps.setInt(2,111);
            int count=ps.executeUpdate();
            //再给占位符传值
            ps.setDouble(1,10000);
            ps.setInt(2,222);
            count+=ps.executeUpdate();
            System.out.println(count==2?"转账成功":"转账失败");
            //程序能够到这里说明以上程序没有异常,事务结束,手动提交数据
            conn.commit();  //提交事务
        } catch (Exception e) {
            //回滚事务
            if(conn!=null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        }  finally {
            //6.释放资源
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

  

posted @ 2021-10-26 20:12  石乐智先生  阅读(50)  评论(0编辑  收藏  举报