JAVA实验3:Java-MySQL实现银行转账系统

该实验通过防止SQL注入攻击提升了用户登录的安全性,并实现了事务管理,关闭了自动提交,启用回滚功能,确保用户资金操作的可靠性。银行应用中,使用Java进行模块化设计,包括数据库建模、用户登录验证、转账操作和资源管理等,确保了转账过程的原子性和一致性。
摘要由CSDN通过智能技术生成

运行结果

实验中解决了用户登录时SQL注入问题,提高了系统的安全性
并且关闭了事务自动提交,开启了事务回滚功能,保证了用户资金的安全性
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

PowerDesigner16.5建模

在这里插入图片描述

数据库源码

drop table if exists userlogin;

/*==============================================================*/
/* Table: userlogin                                             */
/*==============================================================*/
create table userlogin
(
   username             varchar(20) not null,
   password             varchar(20),
   primary key (username)
);

drop table if exists userstate;

/*==============================================================*/
/* Table: userstate                                             */
/*==============================================================*/
create table userstate
(
   username             varchar(20) not null,
   money                bigint,
   primary key (username)
);

insert into userlogin(username,password) values('zrs','333');
insert into userlogin(username,password) values('llf','222');
insert into userstate(username,money) values('zrs',20000);
insert into userstate(username,money) values('llf',0);

使用的java模块

在这里插入图片描述

java源码

Bank主函数入口:

package Bank;

import Mysql.Mysql;
import InitUI.InitUI;
import TransfroUI.*;
import UserLogin.UserLogin;
import java.sql.*;
import java.util.Map;

public class Bank {
    public static void main(String[] args){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try{
            conn = Mysql.connection("bank");
            Map<String,String> map = InitUI.initUI();
            String uname = map.get("username");
            String pwd = map.get("password");
            UserLogin.userLogin(uname,pwd,conn);

            conn.setAutoCommit(false);
            transfor(uname,conn);
            conn.commit();

        }catch(SQLException e){
            if(conn != null){
                try{
                    conn.rollback();
                    System.out.println("事务回滚");
                }catch(Exception a){
                    a.printStackTrace();;
                }
            }
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            Mysql.close(conn,pstmt,rs);
        }
    }

    private static void transfor(String uname,Connection conn) throws SQLException{
        Map<String,String> trans = TransforUI.transforUI();
        String tname = trans.get("transforname");
        String money = trans.get("money");
        String[] sql = {"update userstate set money = money+? where username = ?;",
                        "update userstate set money = money-? where username = ?",
                        "select money from userstate where username = ?"};
        PreparedStatement pstmt_0 = conn.prepareStatement(sql[0]);
        PreparedStatement pstmt_1 = conn.prepareStatement(sql[1]);
        PreparedStatement pstmt_2 = conn.prepareStatement(sql[2]);
        pstmt_0.setString(1,money);
        pstmt_0.setString(2,tname);
        pstmt_1.setString(1,money);
        pstmt_1.setString(2,uname);
        pstmt_2.setString(1,uname);
        int count = pstmt_0.executeUpdate();
        count += pstmt_1.executeUpdate();
        ResultSet rs = pstmt_2.executeQuery();
        rs.next();
        if(count==2 && rs.getInt("money")>=0){
            System.out.println("转账成功");
        }else{
            System.out.println("余额不足");
            throw new SQLException();
        }
    }
}

Mysql封装源码:

package Mysql;

import java.sql.*;

public class Mysql{
    private Mysql(){}

    //注册驱动
    static{
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //连接数据库
    public static Connection connection(String database_name) throws Exception{
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/"+database_name,
                                                "root","feifei123");
    }

    //释放资源
    public static void close(Connection conn, PreparedStatement pstmt){
        if(pstmt != null){
            try{
                pstmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(conn != null){
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }

    //重载释放资源方法
    public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){
        if(rs != null){
            try{
                rs.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(pstmt != null){
            try{
                pstmt.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(conn != null){
            try{
                conn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
}

用户输入模块源码:

package InitUI;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class InitUI {
    private InitUI(){}

    public static Map<String, String> initUI() {
        Map<String,String> map = new HashMap();
        Scanner s = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = s.next();
        System.out.println("请输入密码:");
        String password = s.next();
        map.put("username",username);
        map.put("password",password);
        return map;
    }
}

用户登录检测源码:

package UserLogin;

import java.sql.*;
import java.sql.SQLException;
import java.util.Map;
import java.util.ResourceBundle;


public class UserLogin {
    private UserLogin(){}

    public static void userLogin(String username, String password,Connection conn) throws Exception{
        String sql = "select * from userlogin where username = ? and password = ?;";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,username);
        pstmt.setString(2,password);

        ResultSet rs = pstmt.executeQuery();
        boolean flag = rs.next()==true?true:false;
        if(flag){
            System.out.println(username+"欢迎回来");
        }else{
            System.out.println("登录失败,请重新登录");
            Map<String,String> map =InitUI.InitUI.initUI();
            String uname = map.get("username");
            String pwd = map.get("password");
            userLogin(uname,pwd,conn);
        }
    }
}

用户转账检测源码:

package TransfroUI;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class TransforUI {
    private TransforUI(){}

    public static Map<String, String> transforUI() {
        Map<String,String> map = new HashMap();
        Scanner s = new Scanner(System.in);
        System.out.println("请输入要转账的用户名:");
        String username = s.next();
        System.out.println("请输入要转账的金额:");
        String password = s.next();
        map.put("transforname",username);
        map.put("money",password);
        return map;
    }
}

这是用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、付费专栏及课程。

余额充值