通过银行转账业务体会JAVA与存储过程不同实现方式

任务:帐户表(帐户号,姓名,余额,锁定)。实现帐号1向帐号2转账若干元。

业务要求
1、两个帐户要存在(略)
2、转账方最低余额为10元
3、如果任何一方被锁定(u_lock=1),则不能转
4、要保证交易完整性(不能一个成功,一个失败)


create table T_ACCOUNT
(
  U_ID    NUMBER(5) primary key,
  U_NAME  VARCHAR2(100) not null,
  U_MONEY NUMBER(7) not null,
  U_LOCK  NUMBER(1) default 0
);
insert into T_ACCOUNT (U_ID, U_NAME, U_MONEY, U_LOCK)
values (1, '张三', 900, 0);
insert into T_ACCOUNT (U_ID, U_NAME, U_MONEY, U_LOCK)
values (2, '李四', 100, 0);
insert into T_ACCOUNT (U_ID, U_NAME, U_MONEY, U_LOCK)
values (3, '杨五郎', 3000, 1);
commit;

 

	public void transMoney() throws Exception{
		//操作数据库(业务上的连接对象)
		Connection conn = DBUtil.getNewConn();
		
		//try捕捉的是SQL异常
		try {
			conn.setAutoCommit(false);
			dao.setConn(conn);
			poFrom = dao.getpAccountPo(poFrom.getId());
			poTo = dao.getpAccountPo(poTo.getId());
			
			System.out.println("查询账户完成,请稍侯...");
			new Scanner(System.in).nextLine();
			
			if(poFrom==null || poTo==null){
				throw new Exception("帐户不存在!");
			}
			else if(poTo.getLock()==1 || poFrom.getLock()==1){
				throw new Exception("帐户已被锁定!");
			}
			else if(poFrom.getMoney()-this.money<10){
				throw new Exception("帐户余额不足!");
			}
			
			//转账
			this.poFrom.setMoney(this.poFrom.getMoney()-this.money);
			this.poTo.setMoney(this.poTo.getMoney()+this.money);
			
			dao.updateMoney(poFrom);
			dao.updateMoney(poTo);
			
			//演示:某数据被修改以后不能再被其它用户修改
			System.out.println("确定转账吗(1-确定;其它-取消)?");
			int ok = new Scanner(System.in).nextInt();
			if(ok==1){
				dao.getConn().commit();	
				conn.setAutoCommit(true);
				System.out.println("恭喜,转账成功!");				
			}else{
				dao.getConn().rollback();
				System.out.println("用户取消操作!");
			}

		} catch (SQLException e1) {
			try {
				dao.getConn().rollback();
				System.out.println("出错回滚啦!"+e1.getMessage());
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}finally{
			DBUtil.closeConn(dao.getConn());
		}
	}

 

 

create or replace procedure sp_trans_money
(
p_from number,
p_to   number,
p_money     NUMBER
) 
                                           
is
  v_count  number;
  v_lock  number;
  v_money number;
begin
  --to是否存在
  select count(*) into v_count from t_account where u_id = p_to;
  if v_count = 0 then
    raise_application_error(-20087, '目标用户不存在!');
  end if;
  
    --to是否锁定
  select u_lock into v_lock from t_account where u_id = p_to;
  if v_lock = 1 then
    raise_application_error(-20088, '该用户已锁定!');
  end if;
   
  --from是否存在
  select count(*) into v_count from t_account where u_id = p_from;
  if v_count = 0 then
      raise_application_error(-20087, '转账用户不存在!');
  end if;

  --from是否锁定及余额
  select u_lock, u_money into v_lock, v_money
  from t_account
  where u_id = p_from;
  
  if v_lock = 1 then
    raise_application_error(-20088, '该用户已锁定!');
  elsif (v_money - p_money < 10) then
    raise_application_error(-20089, '该用户余额不足!');
  end if;

   update t_account set u_money = u_money - p_money where u_id = p_from;
   update t_account set u_money = u_money + p_money where u_id = p_to;

   --通常是由存储过程提交事务
   --如果存储过程不提交,则由调用方提交事务
   --好处:可以将多个存储过程放在一个事务中,但通常一个存储过程就是处理一个单独的事务,所以在实际开发中,具体情况具体处理
   --commit;
end;

 

这是用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)); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值