#coding:utf8
import pymysql
class TranferMoney(object):
def __init__(self, conn):
self.conn = conn
#检查账户有效性
def check_acct_available(self, source_acctid):
try:
cursor = self.conn.cursor()
sql_query = "select * from account where acctid='%s'"%source_acctid
cursor.execute(sql_query)
print('check_acct_available:', sql_query)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception('帐号%s不存在'%source_acctid)
finally:
cursor.close()
#检查账户金额
def has_enough_money(self, source_acctid, money):
try:
print(type(money))
cursor = self.conn.cursor()
sql_query = "select * from account where acctid=%s and money >= %d"%(source_acctid, money)
cursor.execute(sql_query)
print('has_enough_money:', sql_query)
rs = cursor.fetchall()
if len(rs) != 1:
raise Exception('帐号%s余额不足'%source_acctid)
finally:
cursor.close()
#账户减款
def reduce_money(self, source_acctid, money):
try:
cursor = self.conn.cursor()
sql_query = "update account set money=money-%d where acctid = '%s'"%(money, source_acctid)
cursor.execute(sql_query)
print('reduce_money:', sql_query)
if cursor.rowcount != 1:
raise Exception('帐号%s减款错误'%source_acctid)
finally:
cursor.close()
#账户加款
def add_money(self, source_acctid, money):
try:
cursor = self.conn.cursor()
sql_query = "update account set money=money+%d where acctid = '%s'"%(money, source_acctid)
cursor.execute(sql_query)
print('reduce_money:', sql_query)
if cursor.rowcount != 1:
raise Exception('帐号%s加款错误'%source_acctid)
finally:
cursor.close()
def transfer(self, source_acctid, target_accid, money):
try:
self.check_acct_available(source_acctid)
self.check_acct_available(target_accid)
self.has_enough_money(source_acctid, money)
self.reduce_money(source_acctid, money)
self.add_money(target_accid, money)
self.conn.commit()
except Exception as e:
print("Exception:", e)
self.conn.rollback()
raise e
if __name__ == '__main__':
source_acctid = input("请输入转账方帐号:")
target_accid = input("请输入收款方帐号:")
money = input("请输入转款金额:")
conn = pymysql.connect(host='localhost', port=3308, user='lmapp', passwd='lmapp', db='test', charset='utf8')
tranfer_money = TranferMoney(conn)
try:
tranfer_money.transfer(source_acctid, target_accid, int(money))
print("转账成功")
except Exception as e:
print('Error:', e)
finally:
conn.close()
评论