1. 程式人生 > >銀行轉賬系統

銀行轉賬系統

import pymysql

class TransferMoney(object):
    def __init__(self,conn):
        self.conn = conn
        self.cur = conn.cursor()


    def transfer(self,source_accid,target_accid,money):
        '''
        :param source_accid:原帳號id
        :param target_accid: 目標帳號id
        :return: bool
        '''
#判斷帳號是否存在 self.check_account_avaiable(source_accid) self.check_account_avaiable(target_accid) #判斷原帳號是否有足夠的錢 self.has_enough_money(source_accid,money) try: #扣錢 self.reduce_money(source_accid,money) #加錢 self.add_money(target_accid,money) self.conn.commit() except
Exception as e: #撤銷對資料庫的操作,回滾 self.conn.rollback() else: print('轉賬成功') def check_account_avaiable(self,accid): '''目標帳號是否存在''' select_sqli = 'select * from bankdata where id=%s' %accid res = self.cur.execute(select_sqli) if
res == 1: return True else: raise Exception('賬戶%s不存在' %accid) def has_enough_money(self,accid,money): '''是否有足夠的錢''' select_sqli = 'select * from bankdata where id=%s' %accid self.cur.execute(select_sqli) res = self.cur.fetchone()[1] if res >= money: return True else: raise Exception('賬戶%s餘額不足' %accid) def reduce_money(self,accid,money): '''對原賬戶的錢進行扣除''' try: update_sqli = 'update bankdata set money=money-%d where id="%s";' %(money,accid) self.cur.execute(update_sqli) except Exception as e: print('error:',e) def add_money(self,accid,money): '''對目標賬戶的錢數進行新增''' try: updata_sqli = 'update bankdata set money=money+%d where id="%s";' %(money,accid) self.cur.execute(updata_sqli) except Exception as e: print('error:',e) def __del__(self): '''當刪除物件時自動執行關閉遊標的操作''' self.cur.close() if __name__=='__main__': conn = pymysql.connect(host='localhost',user='root',password='westos', charset='utf8',db='redhat') tran = TransferMoney(conn) tran.transfer('001','002',1000)

轉賬前的賬戶資訊:

這裡寫圖片描述

轉賬後的賬戶資訊:

這裡寫圖片描述