#-*-coding:utf-8-*-import mysql from MySQL import connector user = ' root ' pwd = ' 123456 ' host = ' 127.0.0.1 ' port = ' 3306 ' db = ' springmvc ' # money Transfer Class class TransferMoney (Object): # constructor def __init__ (self, conn): Self.conn = C Onn # Realize transfer Logic def transfer (self, source_accid, target_accid, money): Try:self.check_acct_avai Lable (source_accid) self.check_acct_available (target_accid) Self.has_enough_money (Source_accid, MO Ney) Self.reduce_money (source_accid, Money) Self.add_money (target_accid, Money) SELF.C Onn.commit () except Exception as E:self.conn.rollback () Raise E # Verify account exists def c Heck_acct_available (self, accid): cursor = self.conn.cursor () try:sql = "SELECT * FROM bank W
Here account =%s "% accid cursor.execute (sql) rs = Cursor.fetchall () If Len (RS)!= 1: Raise EXception ("account%s does not exist"% accid) If Len (rs) = = 1:print ("OK") finally:cursor.c
Lose () # Verify that you have enough money def has_enough_money (self, Accid, money): cursor = Self.conn.cursor () Try: sql = "SELECT * FROM bank WHERE account =%s ' and money >%s '% (Accid, Money) cursor.execute (sq
L) rs = Cursor.fetchall () If Len (RS)!= 1:raise Exception ("Insufficient account%s balance"% accid) If Len (rs) = = 1:print ("OK") Finally:cursor.close () # begins to deduct the money def redu Ce_money (self, Accid, money): cursor = self.conn.cursor () try:sql = "UPDATE Bank SET money =
Money-%s WHERE account =%s '% (Money, accid) cursor.execute (SQL) if Cursor.rowcount!= 1:
Raise Exception ("account%s debit%s failed"% (accid, money)) if Cursor.rowcount = = 1:print ("OK")
Finally Cursor.close () # Start adding Money def add_money (self, Accid, cash): cursor = Self.conn.cursor () Try:
sql = "UPDATE Bank SET Money = $ +%s WHERE account =%s"% (money, accid) cursor.execute (SQL) If Cursor.rowcount!= 1:raise Exception ("account%s plus%s failed"% (accid, money)) if cursor. RowCount = = 1:print ("OK") Finally:cursor.close () # Main method if __name__ = = "__main__
": Print (" Enter transfer ID: ") source_accid = input () print (" Enter account ID: ") target_accid = input () print (" Enter account Amount: ") Money = input () conn = mysql.connector.connect (user = user, password = pwd, host = host, Port = port, DATABASE = db ) Try:tr_money = TransferMoney (conn) Tr_money.transfer (Source_accid, target_accid, money) except Exception as E:print (e) finally:conn.close ()