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)
转账前的账户信息:
转账后的账户信息: