银行转账系统建(结合)数据库
检查用户是否可用,然后检查源账户是否有足够的金额,然后减少源帐户money数量的金额,目标用户增加money的数量,最后提交事务,如果出现错误,那么返回转账前的状态,两个账户金额没有改变。
对于支持事务的数据库,在python数据库的编程中,当游标建立之时,就自动开始了一个隐形的数据库事务。commit()方法游标的所有更新操作,rollback()方法回滚当前游标的所有操作。每一个方法都开始了一个新的事务。
“”"
import pymysql
class TransferMoney(object):
# 构造方法
def __init__(self,conn):
self.conn = conn
self.cur = conn.cursor()
def transfer(self,source_id,target_id,money):
# 1.判断两个银行卡号是否存在
# 2.判断source_id是否有足够的钱
# 3.source_id扣钱
# 4.target_id加钱
if not self.check_account_avaialbe(source_id):
raise Exception("账户不存在")
if not self.check_account_avaialbe(target_id):
raise Exception("账户不存在")
if self.has_enough_money(source_id, money):
try:
self.reduce_money(source_id, money)
self.add_money(target_id, money)
except Exception as e:
print("转账失败:", e)
self.conn.rollback()
else:
self.conn.commit()
print("%s给%s转账%s金额成功" % (source_id,
target_id, money))
def check_account_avaialbe(self, acc_id):
"""判断帐号是否存在, 传递的参数是银行卡号的id"""
select_sqli = "select * from bankData where id=%d;" % (acc_id)
print("execute sql:", select_sqli)
res_count = self.cur.execute(select_sqli)
# res_count:返回数据记录数,只要有一条记录存在,
# 就证明账户存在
if res_count == 1:
return True
else:
return False
def has_enough_money(self, acc_id, money):
"""判断acc_id账户上金额> money"""
# 查找acc_id存储金额?
select_sqli = "select money from bankData where id=%d;" % (acc_id)
print("execute sql:", select_sqli)
self.cur.execute(select_sqli) # ((100, 100), )
# 获取查询到的金额钱数
# acc_moneys = self.cur.fetchone()
# print(acc_moneys)
acc_money = self.cur.fetchone()[0]
print(acc_money)
# 判断
if acc_money >= money:
return True
else:
return False
def add_money(self, acc_id, money):
update_sqli = "update bankData set money=money+%d where id=%d" % (money, acc_id)
print("add money:", update_sqli)
self.cur.execute(update_sqli)
def reduce_money(self, acc_id, money):
update_sqli = "update bankData set money=money-%d where id=%d" % (money, acc_id)
print("reduce money:", update_sqli)
self.cur.execute(update_sqli)
# 析构方法
def __del__(self):
self.cur.close()
self.conn.close()
# 1. 连接数据库,
conn = pymysql.connect(
host='localhost',
user='root',
password='redhat',
db='westos',
charset='utf8',
autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。
)
trans = TransferMoney(conn)
#trans.add_money(100,200)
# trans.transfer(100,200,10)
#trans.has_enough_money(100,270)
test
"""
把测试内容不被别人看
你写好的类别人也可以运行,不会有杂七杂八的东西
注意:写好的类的文件名称应该是test,另一个文件可以直接import test导入文件
"""
def hello():
print('hello')
#hello()
#print(__name__)
if __name__ == '__main__':
hello()
#外部框架flask
#把代码放在网上