python3.7+PyCharm+mysql银行转账完整代码,拿走时请扣1
# coding:utf8
import sys
import pymysql
class TransferMoney(object):
def __init__(self, conn):
self.conn = conn
def check_acct_available(self, accountid):
cursor = conn.cursor()
try:
sql = "select * from account where accountid=%s" % accountid
cursor.execute(sql)
arr = cursor.fetchall()
if len(arr) != 1:
raise Exception("账号%s不存在" % accountid)
print("验证账号%s存在" % accountid)
finally:
cursor.close()
def has_enough_money(self, accountid, money):
cursor = conn.cursor()
try:
sql = "select * from account where accountid=%s and money>=%s" % (accountid, money)
cursor.execute(sql)
arr = cursor.fetchall()
if len(arr) != 1:
raise Exception("账号%s余额不足" % accountid)
print("验证账号%s有足够的余额" % accountid)
finally:
cursor.close()
def reduce_money(self, accountid, money):
cursor = conn.cursor()
try:
sql = "update account set money=money-%s where accountid=%s" % (money, accountid)
cursor.execute(sql)
arr = cursor.rowcount
if arr != 1:
raise Exception("账号%s减款失败" % accountid)
print("账号%s减款%s成功" % (accountid, money))
finally:
cursor.close()
def add_money(self, accountid, money):
cursor = conn.cursor()
try:
sql = "update account set money=money+%s where accountid=%s" % (money, accountid)
cursor.execute(sql)
arr = cursor.rowcount
if arr != 1:
raise Exception("账号%s加款失败" % accountid)
print("账号%s加款%s成功" % (accountid, money))
finally:
cursor.close()
def transfer(self, source_accountid, target_accountid, money):
try:
self.check_acct_available(source_accountid)
self.check_acct_available(target_accountid)
self.has_enough_money(source_accountid, money)
self.reduce_money(source_accountid, money)
self.add_money(target_accountid, money)
conn.commit()
except Exception as e:
conn.rollback()
raise e
if __name__ == "__main__":
# source_accountid = sys.argv[1]
# target_accountid = sys.argv[2]
# money = sys.argv[3]
print('请输入付款人账号:')
source_accountid = input()
print('请输入收款人账号:')
target_accountid = input()
print('请输入转账金额:')
money = input()
conn = pymysql.connect(
host="localhost",
user="root",
passwd="123456",
db="qiushan",
charset="utf8"
)
# 转账操作对象
tr_money = TransferMoney(conn)
try:
# 转账操作
tr_money.transfer(source_accountid, target_accountid, money)
print("转账完成")
except Exception as e:
print("出现了问题:" + str(e))
finally:
conn.close()account表内容:

