mysql for python,银行转账模拟
学习中, 本人为初学者。勿喷。
#-*- coding:utf-8 -*- import MySQLdb class Tranferaccount(object): def __init__(self,sqlcon): self.sqlcon = sqlcon def account_check_avaiable(self,accid): cursor = self.sqlcon.cursor() sql_str = "select * from account where accid = %s "% accid try: print 'account_check_avaiable:%s'%sql_str cursor.execute(sql_str) rs = cursor.fetchall() if len(rs)!=1: raise Exception('此账号%s不存在'%accid) finally: cursor.close() def account_enough_money(self,accid,money): cursor = self.sqlcon.cursor() sql_str = "select * from account where accid = %s and money >%s "% (accid,money) try: print 'account_enough_money:%s'%sql_str cursor.execute(sql_str) rs = cursor.fetchall() if len(rs)!=1: raise Exception('此账号%s余额不足'%accid) finally: cursor.close() def account_reduce_money(self,accid,money): cursor = self.sqlcon.cursor() sql_str = "update account set money = money-%s where accid = %s "% (money,accid) try: print 'account_reduce_money:%s'%sql_str cursor.execute(sql_str) if cursor.rowcount != 1: raise Exception('此账号%s减款失败'%accidd) finally: cursor.close() def account_add_money(self,accid,money): cursor = self.sqlcon.cursor() sql_str = "update account set money = money+%s where accid = %s "% (money,accid) try: print 'account_add_money:%s'%sql_str cursor.execute(sql_str) if cursor.rowcount != 1: raise Exception('此账号%s加款失败'%accid) finally: cursor.close() def tranfer(self,source_accid,dest_accid,money): try: self.account_check_avaiable(source_accid) self.account_check_avaiable(dest_accid) self.account_enough_money(source_accid,money) self.account_reduce_money(source_accid,money) self.account_add_money(dest_accid,money) self.sqlcon.commit() except Exception as e: self.sqlcon.rollback() raise e if __name__ == "__main__": source_accid = 11 dest_accid = 12 money = 100 conn = MySQLdb.connect(host='127.0.0.1',user='root',db = 'liunx',passwd='root',port=3306,charset='utf8') tr_money = Tranferaccount(conn) try: tr_money.tranfer(source_accid,dest_accid,money) except Exception as e: print '出现问题:%s'% e finally: conn.close()