学习银行转账系统-代码摘取csdn

11 篇文章 0 订阅
10 篇文章 0 订阅

变成思想理解

1数据库:2个字段,名字和余额

2.程序设计部分 ,例如A转账20到B账户 ,实现方法A余额-20,B余额增加20即可

代码不是自己缩写,在原有基础上做了修改,并加了具体代码注释

官方代码如下(代码有点小多,不过注释解释的很明白了,不明白可以私信 我,经过调整,运行正常,这次是固定金额的,等下次设置自定义金额,原账户,和目标账户,做一个交互式系统):

#银行转账系统,参数,原卡号,新卡号,转账金额

#先建立数据库test_3和表bankdata
#加载mysql相关类包mysql或者pymysql
import pymysql
#数据库配置信息,存储格式字典
def Conn():
    config = {
    #本机ip
    'host': '127.0.0.1',
    #mysql固定端口3306
    'port': 3306,
    #数据用户名,密码,编码格式
    'user': 'root',
    'passwd': '1234',
    'charset':'utf8',

    }
    #数据建立链接对象常用方法
    conn = pymysql.connect(**config)
    #数据库创建游标方法
    cursor = conn.cursor()

    try:
        #用python创建数据库语句,在学习中,下次有机会自己模仿编写下
        #创建数据库
        DB_NAME = 'test_3'
        #执行数据库语句有游标对象执行
        cursor.execute('DROP DATABASE IF EXISTS %s' %DB_NAME)
        cursor.execute('CREATE DATABASE IF NOT EXISTS %s' %DB_NAME)
        conn.select_db(DB_NAME)

        #创建表也是同上,游标对象,里面%s是字符串格式化操作,之前学习过
        TABLE_NAME = 'bankData'
        cursor.execute('CREATE TABLE %s(id int primary key,money int(30))' %TABLE_NAME)

        #批量插入纪录,批量插入方法利用列表[元祖1,元祖2]进行批量插入操作
        values = []
        for i in range(20):
            values.append((int(i),int(156*i)))
        cursor.executemany('INSERT INTO bankData values(%s,%s)',values)
        #出了查询有fetchall,其他操作需要提交事物
        conn.commit()

        #查询数据条目
        count = cursor.execute('SELECT * FROM %s' %TABLE_NAME)
        print ('total records:{}'.format(cursor.rowcount))

        #获取表名信息
        desc = cursor.description
        print ("%s %3s" % (desc[0][0], desc[1][0]))
        #scroll方法是游标滚动到第10个位置
        cursor.scroll(10,mode='absolute')
        results = cursor.fetchall()
        for result in results:
            print (result)

    except:
        import traceback
        traceback.print_exc()

        #发生错误时会滚
        conn.rollback()
    finally:

        #关闭游标连接
        cursor.close()

        #关闭数据库连接
        conn.close()

#构建系统

import pymysql
#转账类实现方法,操作上面的方法
class TransferMoney(object):

    #构造方法:注意的是要有__,之前版本可那个直接init就可以,但是这个版本不可以
    def __init__(self, conn):
        self.conn = conn
        self.cur = conn.cursor()
    #实现方法,第一判断人物是否存在
    def transfer(self, source_id, target_id, money):
        if not self.check_account_avaialbe(source_id):
            raise Exception("账户不存在")
        if not self.check_account_avaialbe(target_id):
            raise Exception("账户不存在")
        #第二判断有足够余额,具体方法在下面介绍
        if self.has_enough_money(source_id, money):
            try:#减少增加转账金额
                self.reduce_money(source_id, money)
                self.add_money(target_id, money)
            except Exception as e:
                print("转账失败:", e)
                self.conn.rollback()
        else:
            self.conn.commit()
            print("%s给%s转账%s金额成功" % (source_id, target_id, money))

    def check_account_avaialbe(self, acc_id):
        """判断帐号是否存在, 传递的参数是银行卡号的id"""
        select_sqli = "select * from bankData where id=%d;" % (acc_id)
        print("execute sql:", select_sqli)
        res_count = self.cur.execute(select_sqli)
        if res_count == 1:
            return  True
        else:
            raise Exception("账户%s不存在" %(acc_id))
            return False

    def has_enough_money(self, acc_id, money):
        """判断acc_id账户上金额> money"""

        #查找acc_id存储金额?
        select_sqli = "select money from bankData where id=%d;" % (acc_id)
        print("execute sql:", select_sqli)
        self.cur.execute(select_sqli) # ((1, 500), )

        #获取查询到的金额钱数;fetchone百度下就是查询返回值单个元祖,就是一行记录,500
        acc_money = self.cur.fetchone()[0]

        #判断
        if acc_money >= money:
            return True
        else:
            return False

    def add_money(self, acc_id, money):
        update_sqli = "update bankData set money=money+%d where id=%d" % (money, acc_id)
        print("add money:", update_sqli)
        self.cur.execute(update_sqli)

    def reduce_money(self, acc_id, money):
        update_sqli = "update bankData set money=money-%d where id=%d" % (money, acc_id)
        print("reduce money:", update_sqli)
        self.cur.execute(update_sqli)

    #析构方法
    def __del__(self):
        self.cur.close()
        self.conn.close()

if __name__ == '__main__':

    #1. 连接数据库,
    conn = pymysql.connect(host = '127.0.0.1' # 连接名称,默认127.0.0.1
    ,user = 'root' # 用户名
    ,passwd='1234' # 密码
    ,port= 3306 # 端口,默认为3306
    ,db='test_3' # 数据库名称
    ,charset='utf8'
    ,autocommit=True, # 如果插入数据,自动提交给数据库
    )
    trans = TransferMoney(conn)
    trans.transfer(15, 12, 200)

  • 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
发出的红包

打赏作者

长夜漫漫长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值