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.首先需要判断银行卡是否存在
if not self.check_acccount(source_id):
raise Exception("%s账户不存在" %(source_id))
if not self.check_acccount(target_id):
raise Exception("%s账户不存在" %(target_id))
# 2.判断source_id是否有足够的钱
if self.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))
# 判断帐号是否存在, 传递的参数是银行卡号的id
def check_acccount(self,acc_id):
sele_sql="select * from bankdata where id=%d;" %(acc_id)
res_count=self.cur.execute(sele_sql)
if res_count ==1:
return True
else:
return False
# 查看账户是否有足够的钱
def enough_money(self,acc_id,money):
select_sql="select money from bankdata where id=%s" %(acc_id)
self.cur.execute(select_sql)
acc_money=self.cur.fetchone()[0]
if acc_money>=money:
return True
else:
return False
# 给账户增加钱
def add_money(self,acc_id,money):
update_sql="update bankdata set money=money+%d where id=%d " %(money,acc_id)
self.cur.execute(update_sql)
# 给账户减少钱
def reduce_money(self,acc_id,money):
reduce_sql="update bankdata set money=money-%d where id=%d " %(money,acc_id)
self.cur.execute(reduce_sql)
# 析构方法,关闭数据库游标指针,关闭数据库连接,
def __del__(self):
self.cur.close()
self.conn.close()
if __name__ == '__main__':
conn = pymysql.connect(
host="localhost",
user="root",
passwd="yu",
db="py_stud",
charset="utf8",
autocommit=True
)
trans=TransferMoney(conn)
trans.transfer(1112,1113,100)
python---mariadb---微型银行转账系统
最新推荐文章于 2022-05-29 18:22:48 发布