1 #Coding=utf-82 ImportSYS3 ImportMySQLdb4 5 classTransferMoney (object):6 def __init__(self,conn):7Self.conn =Conn8 9 #Check if the account is legalTen defcheck_acct_avaiable (self,acctid): Onecursor =self.conn.cursor () A Try: -sql ="SELECT * from account where acctid=%s"%Acctid - cursor.execute (SQL) the Print "Check Account:"+SQL -rs =Cursor.fetchall () - ifLen (rs)! = 1: - RaiseException ("Account %s Illega"%Acctid) + finally: - cursor.close () + A #Check if there's enough money at defHas_enough_money (Self,acctid,money): -cursor =self.conn.cursor () - Try: -sql ="SELECT * from account where acctid=%s and money >%s"%(Acctid,money) - cursor.execute (SQL) - Print "Have enough money:"+SQL inrs =Cursor.fetchall () - ifLen (rs)! = 1: to RaiseException ("Account %s isn't enough money"%Acctid) + finally: - cursor.close () the * #account minus Money $ defReduce_money (Self,acctid,money):Panax Notoginsengcursor =self.conn.cursor () - Try: thesql ="Update account Set money = money-%s where Acctid =%s"%(Money,acctid) + cursor.execute (SQL) A Print "Reduce_money:"+SQL the ifCursor.rowcount! = 1: + RaiseException ("reduce money fail%s"%Acctid) - finally: $ cursor.close () $ - #Account plus Money - defAdd_money (Self,acctid,money): thecursor =self.conn.cursor () - Try:Wuyisql ="Update account Set money = money+%s where Acctid =%s"%(Money,acctid) the cursor.execute (SQL) - Print "Add_money:"+SQL Wu ifCursor.rowcount! = 1: - RaiseException ("add Money fail%s"%Acctid) About finally: $ cursor.close () - #Main execution Statement - defTransfer (Self,source_acctid,target_acctid,money): - Try: A self.check_acct_avaiable (Source_acctid) + self.check_acct_avaiable (Target_acctid) the Self.has_enough_money (Source_acctid,money) - Self.reduce_money (Source_acctid,money) $ Self.add_money (Target_acctid,money) the Self.conn.commit () the exceptException as E: the Self.conn.rollback () the Raisee - in if __name__=="__main__": theSource_acctid = sys.argv[1] theTarget_acctid = sys.argv[2] AboutMoney = Sys.argv[3] theconn = MySQLdb.connect (host ='127.0.0.1', port=3306,user='Root', passwd="', db='Test', charset='UTF8') theTr_money =TransferMoney (conn) the + Try: - Tr_money.transfer (Source_acctid,target_acctid,money) the exceptException as E:Bayi Print "happen:"+Str (e) the finally: theConn.close ()
Python a complete set of transactional operations