Java模拟银行转账(操作事务)

第一步:建立一张银行账户表 叫 BankAccount 并建立一个序列

id         number    pk         //用户id
ano        varchar2(30)  uk     //用户卡号
apassword  varchar2(30)         //用户密码
aname      varchar2(30)         //用户名
amoney     number               //余额

//创建银行用户表
drop table bank_account;
create table    bank_account(
     id    number  constraint   bank_account_id_pk   primary key,
     ano  varchar(30) constraint bank_account_ano_uk  unique,
     apassword  varchar(30), 
     aname   varchar(30),
     amoney  number
);
drop sequence bank_account_id_seq;
create sequence    bank_account_id_seq;
6.2 写一个java程序  用来开户   只要输入 账号                  密码     开户人的姓名   余额 
开户信息如下                           6225880111887788     123456   zhangsan       99999999  
                                      6225880111887799     123456   lisi    9  

第二步:创建Bean包,编写实体类

public class BankAccount {
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getAno() {
        return ano;
    }
    public void setAno(String ano) {
        this.ano = ano;
    }
    public String getAname() {
        return aname;
    }
    public void setAname(String aname) {
        this.aname = aname;
    }
    public String getApassword() {
        return apassword;
    }
    public void setApassword(String apassword) {
        this.apassword = apassword;
    }
    public String getAmoney() {
        return amoney;
    }
    public void setAmoney(String amoney) {
        this.amoney = amoney;
    }
    @Override
    public String toString() {
        return "BankAccount [id=" + id + ", ano=" + ano + ", aname=" + aname + ", apassword=" + apassword + ", amoney="
                + amoney + "]";
    }
    public BankAccount(String ano, String aname, String apassword, String amoney) {
        super();
        this.ano = ano;
        this.aname = aname;
        this.apassword = apassword;
        this.amoney = amoney;
    }
    public BankAccount(int id, String ano, String aname, String apassword, String amoney) {
        super();
        this.id = id;
        this.ano = ano;
        this.aname = aname;
        this.apassword = apassword;
        this.amoney = amoney;
    }
    public BankAccount() {
        super();
        // TODO Auto-generated constructor stub
    }
    private int id;
    private String ano;
    private String aname;
    private String apassword;
    private String amoney;
}

第三步:创建账号,编写开户程序

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import com.xdl.util.JdbcUtil2;

public class CreateBankAccount {
    public static void main(String[] args) {
         Scanner  sc = new Scanner(System.in);
         System.out.println("请输入开户的卡号:");
         String  ano = sc.nextLine();
         System.out.println("请输入开户的名字:");
         String  aname = sc.nextLine();
         System.out.println("请输入开户的密码:");
         String  apassword = sc.nextLine();
         System.out.println("请输入开户的钱数:");
         String  smoney = sc.nextLine();
         //double  amoney = Double.parseDouble(smoney);
         // 把输入的数据 包装成对象  
         BankAccount  ba = new BankAccount(ano, aname, apassword, smoney);
         Connection  conn = null;
         PreparedStatement  ps = null;
         conn = JdbcUtil2.getConnection();
         String  sql="insert into bank_account values(bank_account_id_seq.nextval,?,?,?,?)";
         try {
            ps = conn.prepareStatement(sql);
            ps.setString(1, ba.getAno());
            ps.setString(2, ba.getApassword());
            ps.setString(3, ba.getAname());
            ps.setDouble(4, Double.parseDouble(ba.getAmoney()));
            int rows = ps.executeUpdate();
            if(rows == 1) {
                System.out.println("开户成功");
            }else{
                System.out.println("开户失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcUtil2.releaseResource(conn, ps, null);
        }
    }
}

第四步:编写转账程序

1、先登录,登录成功才可以执行转账程序

2、转账逻辑时,链接会自动进行数据的提交,这样万一转入的账户不成功,则无法回退之前的操作,为了解决 操作语句 需要同时成功或同事失败 则需要关闭连接的自动提交

禁止自动提交 conn.setAutoCommit(false);
语句都成功 就提交 conn.commit() ;否则进行回滚 conn.rollback();

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import com.xdl.util.JdbcUtil2;

public class BankAccountTransfer {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入登录的卡号:");
        String  ano  = sc.nextLine();
        System.out.println("请输入登录的密码:");
        String  apassword = sc.nextLine();
        Connection  conn = null;
        PreparedStatement ps = null;
        /* 定义两个转账的  PreparedStatement */
        PreparedStatement from = null;
        PreparedStatement to = null;
        ResultSet  rs = null;
        BankAccount  ba = null;
        conn = JdbcUtil2.getConnection();
        String  sql="select * from bank_account where ano=? and apassword=?";
        try {
            ps=conn.prepareStatement(sql);
            ps.setString(1, ano);
            ps.setString(2, apassword);
            rs = ps.executeQuery();
            if(rs.next()){
                ba = new BankAccount(rs.getInt("id"),
                   rs.getString("ano"), rs.getString("aname"), rs.getString("apassword"),
                   rs.getString("amoney"));
            }
            if(ba!=null){
                System.out.println("登录成功");
                // 从当前账户中扣除输入的金额
                System.out.println("请输入转账的金额:");
                String  smoney=sc.nextLine();
                double  money = Double.parseDouble(smoney);
                sql="update  bank_account set amoney=amoney-? where ano=?";
                // 禁止自动提交  
                conn.setAutoCommit(false);
                from = conn.prepareStatement(sql);
                from.setDouble(1, money);
                from.setString(2, ba.getAno());
                int  fromf=from.executeUpdate();
                // 提示用户输入转入的账号  和  账户名
                System.out.println("请输入收款的账号:");
                String  toano = sc.nextLine();
                System.out.println("请输入收款人姓名:");
                String  toaname= sc.nextLine();
                sql="update  bank_account set amoney=amoney+? where ano=? and aname=?";
                to=conn.prepareStatement(sql);
                to.setDouble(1, money);
                to.setString(2, toano);
                to.setString(3, toaname);
                int tof = to.executeUpdate();
                if(fromf==1 && tof==1){
                    System.out.println("转账成功");
                    conn.commit(); //提交
                }else{
                    System.out.println("转账失败");
                    conn.rollback(); //回滚
                }
            }else{
                System.out.println("登录失败");
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            JdbcUtil2.releaseResource(conn, ps, rs);
            JdbcUtil2.releaseResource(conn, from, null);
            JdbcUtil2.releaseResource(conn, to, null);
        }
    }
}
  • 5
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
这是用Java编写的一个简单的银行转账系统,包括取款,存款,转账等功能,其中用到了数据库的连接,采用Eclipse编写,包含数据库的设计文件。非常适合有一定基础的Java初学者使用。 package com.gujunjia.bank; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.sql.*; /** * * @author gujunjia */ public class DataBase { static Connection conn; static PreparedStatement st; static ResultSet rs; /** * 加载驱动 */ public static void loadDriver() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("加载驱动失败"); } } /** * 创建数据库的连接 * * @param database * 需要访问的数据库的名字 */ public static void connectionDatabase(String database) { try { String url = "jdbc:mysql://localhost:3306/" + database; String username = "root"; String password = "gujunjia"; conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { System.out.println(e.getMessage()); } } /** * 关闭数据库连接 */ public static void closeConnection() { if (rs != null) { // 关闭记录集 try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (st != null) { // 关闭声明 try { st.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { // 关闭连接对象 try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } package com.gujunjia.bank; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 本类主要实现整个系统的界面 * * @author gujunjia */ public class MainFrame extends JFrame implements ActionListener, FocusListener { /** * */ private static final long serialVersionUID = 1L; public static String userId; JTextField userIdText; JPasswordField passwordText; JButton registerButton; JButton logInButton; public MainFrame() { super("个人银行系统"); this.setSize(400, 500); this.setLocation(getMidDimension(new Dimension(400, 500))); getAppearance(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * 获取屏幕的中间尺寸 * * @param d * Dimension类型 * @return 一个Point类型的参数 */ public static Point getMidDimension(Dimension d) { Point p = new Point(); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); p.setLocation((dim.width - d.width) / 2, (dim.height - d.height) / 2); return p; } /** * 布局 * * @return Container */ public Container getAppearance() { Container container = this.getContentPane(); container.setLayout(new GridLayout(4, 0)); JLabel label1 = new JLabel("个人银行系统"); label1.setFont(new Font("楷体", Font.BOLD, 40)); JLabel label2 = new JLabel("账号:"); label2.setFont(new Font("楷体", Font.PLAIN, 15)); JLabel label3 = new JLabel("密码:"); label3.setFont(new Font("楷体", Font.PLAIN, 15)); userIdText = new JTextField(20); userIdText.addFocusListener(this); passwordText = new JPasswordField(20); passwordText.addFocusListener(this); JPanel jp1 = new JPanel(); JPanel jp2 = new JPanel(); JPanel jp3 = new JPanel(); JPanel jp4 = new JPanel(); jp1.add(label1); jp2.add(label2); jp2.add(userIdText); jp3.add(label3); jp3.add(passwordText); registerButton = new JButton("注册"); registerButton.addActionListener(this); registerButton.setFont(new Font("楷体", Font.BOLD, 15)); logInButton = new JButton("登录"); logInButton.addActionListener(this); logInButton.setFont(new Font("楷体", Font.BOLD, 15)); jp4.add(registerButton); jp4.add(logInButton); container.add(jp1); container.add(jp2); container.add(jp3); container.add(jp4); return container; } public void actionPerformed(ActionEvent e) { Object btn = e.getSource(); if (btn == registerButton) { new Register(); } else if (btn == logInButton) { String id = userIdText.getText().trim(); String password = new String(passwordText.getPassword()); Bank bank = new Bank(); if (id.equals("") || password.equals("")) { JOptionPane.showMessageDialog(null, "请输入账号和密码"); } else { String dPassword = bank.getPassword(id); if (password.equals(dPassword)) { userId = id; this.dispose(); new UserGUI(); } else { JOptionPane.showMessageDialog(this, "密码或用户名错误", "错误", JOptionPane.ERROR_MESSAGE); } } } } @Override public void focusGained(FocusEvent e) { Object text = e.getSource(); if (text == userIdText) { userIdText.setText(""); userIdText.setFont(new Font("宋体", Font.BOLD, 15)); } else if (text == passwordText) { passwordText.setText(""); } } @Override public void focusLost(FocusEvent e) { Object text = e.getSource(); if (text == userIdText) { if (userIdText.getText().equals("")) { userIdText.setText("请输入账号"); userIdText.setFont(new Font("楷体", Font.ITALIC, 15)); } } } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值