JDBC_银行代码

//1
public interface IAccountService {
    /*增加账户,删除账户,查询余额,存款,取款,转帐*/
    public void createAccount(Account act);
    public void removeAccount(String actNo);
    public double getBal(String actNo);
    public void deposite(String actNo,double amount);
    public void withdraw(String actNo,double amount);
    public void transfer(String from ,String to, double amount);
}
//2
public class Account {
    private String actNo;
    private double bal;
    public void deposite(double amount){
        bal = bal + amount;
    }
    public void withdraw(double amount){
        bal = bal - amount;
        
    }
    public Account(String actNo, double bal) {
        super();
        this.actNo = actNo;
        this.bal = bal;
    }
    public String getActNo() {
        return actNo;
    }
    public void setActNo(String actNo) {
        this.actNo = actNo;
    }
    public double getBal() {
        return bal;
    }
    public void setBal(double bal) {
        this.bal = bal;
    }
}
//3
public interface IAccountDAO {
     public void insert(Account act,Connection con) throws DataException;
     public void del(String actNo,Connection con) throws DataException;
     public void update(Account act, Connection con) throws DataException;
     public Account findAccountByActNo(String actNo,Connection con) throws DataException;
}
//4
public class DataException extends Exception {

    public DataException() {
        // TODO Auto-generated constructor stub
    }

    public DataException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public DataException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public DataException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}
//5
public class AccountServiceJdbcImpl implements IAccountService {
    private IAccountDAO dao = AccountDAOFactory.getDAO();
    public void createAccount(Account act) {
        Connection con = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            dao.insert(act, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }

    }

    public void deposite(String actNo, double amount) {
        Connection con = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            Account act = dao.findAccountByActNo(actNo, con);
            act.deposite(amount);
            dao.update(act, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }


    }

    public double getBal(String actNo) {
        Connection con = null;
        double bal = 0.0;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            Account act = dao.findAccountByActNo(actNo, con);
            bal = act.getBal();
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }

        return bal;
    }

    public void removeAccount(String actNo) {
        Connection con = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            dao.del(actNo, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }


    }

    public void transfer(String from, String to, double amount) {
        Connection con = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            Account a1 = dao.findAccountByActNo(from, con);
            Account a2 = dao.findAccountByActNo(to, con);
            a1.withdraw(amount);
            a2.deposite(amount);
            dao.update(a1, con);
            dao.update(a2, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }


    }

    public void withdraw(String actNo, double amount) {
        Connection con = null;
        try {
            con = JdbcUtil.getConnection();
            con.setAutoCommit(false);
            Account act = dao.findAccountByActNo(actNo, con);
            act.withdraw(amount);
            dao.update(act, con);
            con.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                 e1.printStackTrace();
            }
        }finally{
            JdbcUtil.release(con);
        }


    }

}
//6

public class AccountDAOJdbcImpl implements IAccountDAO {

    public void del(String actNo, Connection con) throws DataException {
        String sql = "delete from t_act where actNo=?";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, actNo);
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new DataException("del error");
        }finally{
            JdbcUtil.release(ps);
        }

    }

    public Account findAccountByActNo(String actNo, Connection con)
            throws DataException {
        String sql = "select actNo,bal from t_act" +
                " where actNo=?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        Account act = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, actNo);
            rs = ps.executeQuery();
            if(rs.next()){
                act = 
                   new Account(rs.getString(1),rs.getDouble(2));            
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new DataException("find error");
        }finally{
            JdbcUtil.release(rs,ps,null);
        }
        return act;
    }

    public void insert(Account act, Connection con) throws DataException {
        String sql = "insert into t_act values(?,?)";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, act.getActNo());
            ps.setDouble(2, act.getBal());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new DataException("insert error");
        }finally{
            JdbcUtil.release(ps);
        }

    }

    public void update(Account act, Connection con) throws DataException {
        String sql = "update t_act set actNo=?,bal=? " +
                "where actNo=?";
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, act.getActNo());
            ps.setDouble(2, act.getBal());
            ps.setString(3,act.getActNo());
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            throw  new DataException("update error");
        }finally{
            JdbcUtil.release(ps);
        }

    }

}
//7
public class AccountDAOFactory {
    public static IAccountDAO getDAO(){
        return new AccountDAOJdbcImpl();
    }
}
//8
public class AccountServiceFactory {
    public static IAccountService getService(){
        return new AccountServiceJdbcImpl();
    }
}
//9
public class Test {
    public static void main(String[] args) {
        IAccountService s = AccountServiceFactory.getService();
        s.createAccount(new Account("a-001",12000.0));
        s.createAccount(new Account("a-002",7000.0));
        StringBuffer sb = new StringBuffer();
        
        sb.append("a-001="+s.getBal("a-001")+"\n");
        sb.append("a-002="+s.getBal("a-002")+"\n");
        sb.append("从a-001转756.0到a-002\n");
        s.transfer("a-001", "a-002", 756.0);
        sb.append("a-001="+s.getBal("a-001")+"\n");
        sb.append("a-002="+s.getBal("a-002")+"\n");
        
        System.out.print(sb.toString());    
        
    }

}
//10
JdbcUtil工具类

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是用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、付费专栏及课程。

余额充值