资金管理系统——python
- 下面是用python实现的一个资金管理系统
- 使用PyMySql连接操作数据库,根据数据库内的信息进行登录判断。成功登录后进入系统欢迎页面,同时为成功登录的用户创建一个用户对象,根据用户做出的操作执行相应的方法,并同步到数据库中,在操作结束后将此次操作打印出来(写入本地文件),类似于下面这样:
- 本文章只是把在pyhon中写的所有代码存了一下方便以后使用,大家也可以看看,其实应该还需要先创建数据库类的东西,等我有时间了会在我人工智能专栏中进行详细讲解的,但是我写的时候时间比较长,怕大家等不及,所以就先把这个代码给大家。
import time
import sys
import pymysql
action_dict = {1: "存款", 2: "取款", 3: "转账", 4: "修改密码", 5: "退出"}
user_balances = {}
user_passwords = {}
def con_mysql(sql, params=None):
try:
db = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='money'
)
cursor = db.cursor()
if params:
cursor.execute(sql, params)
else:
cursor.execute(sql)
results = cursor.fetchone()
db.commit()
return results
except pymysql.Error as e:
if e.args[0] == 1062:
print("数据库操作出现重复键等错误:", e)
elif e.args[0] == 1406:
print("数据库操作出现数据长度等错误:", e)
else:
print("数据库操作出现其他错误:", e)
db.rollback()
sys.exit()
finally:
db.close()
def check_password(username, password):
"""
验证旧密码是否正确
参数:
username (str): 用户名
password (str): 用户输入的旧密码
返回:
bool: 如果密码正确返回True,否则返回False
"""
sql = "SELECT pwd FROM user WHERE username = %s"
result = con_mysql(sql, (username,))
if result:
stored_password = result[0]
if stored_password and stored_password == password:
return True
return False
def update_password(username, new_password):
"""
更新用户密码
参数:
username (str): 用户名
new_password (str): 用户输入的新密码
"""
sql = "UPDATE user SET pwd = %s WHERE username = %s"
con_mysql(sql, (new_password, username))
print(f"已成功更新用户 {username} 的密码。")
def update_balance(target_username, transfer_amount):
"""
通过数据库操作更新目标用户的账户余额
参数:
target_username (str): 转账目标用户的用户名
transfer_amount (float): 转账的金额
"""
try:
connection = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='money'
)
try:
with connection.cursor() as cursor:
query = "SELECT balance FROM user WHERE username = %s"
cursor.execute(query, (target_username,))
result = cursor.fetchone()
if result:
current_balance = result[0]
new_balance = current_balance + transfer_amount
update_query = "UPDATE user SET balance = %s WHERE username = %s"
cursor.execute(update_query, (new_balance, target_username))
connection.commit()
return True, new_balance
else:
return False, None
finally:
connection.close()
except pymysql.Error as e:
print(f"数据库操作出现错误: {e}")
return False, None
class Account(object):
def __init__(self, username, money, number=0):
self.money = money
self.username = username
self.start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.number = number
def save(self):
self.money += self.number
print(f"已存入%.2f元,当前余额为%.2f元" % (self.number, self.money))
return True
def take(self):
if self.number > self.money:
print("余额不足")
return False
else:
self.money -= self.number
print(f"取出%f元,当前余额为%.2f元" % (self.number, self.money))
return True
def update(self):
old_password = input("请输入旧密码:")
new_password = input("请输入新密码:")
if check_password(self.username, old_password):
update_password(self.username, new_password)
print("密码修改成功!")
else:
print("旧密码错误,密码修改失败!")
def implement(self):
latest_balance_result = con_mysql("SELECT balance FROM user WHERE username = %s", (self.username,))
if latest_balance_result:
self.money = latest_balance_result[0]
print("请选择操作:")
for num, action in action_dict.items():
print(f"{num}. {action}")
while True:
try:
action = int(input("请输入对应操作编号(1 - 5):"))
if action in range(1, 6):
break
else:
print("请输入1到5之间的整数作为操作指令哦,请重新输入。")
except ValueError:
print("您输入的不是合法的整数,请重新输入正确的操作指令。")
if action == 5:
sys.exit()
elif action == 1:
while True:
try:
self.number = float(input("请输入存入的金额:"))
break
except Exception as e:
print("请输入正确的金额")
if self.save():
sql = "UPDATE user SET balance = %s WHERE username = %s"
con_mysql(sql, (self.money, self.username))
self.voucher(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), action)
elif action == 2:
while True:
try:
self.number = float(input("请输入取出的金额"))
break
except Exception as e:
print("请输入正确的金额")
if self.take():
sql = "UPDATE user SET balance = %s WHERE username = %s"
con_mysql(sql, (self.money, self.username))
self.voucher(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), action)
else:
print("取款操作失败,不生成凭证。")
elif action == 3:
transfer_username = input("请输入转账目标用户名:")
transfer_amount = None
while True:
try:
transfer_amount = float(input("请输入转账金额:"))
break
except Exception as e:
print("请输入正确的金额")
if transfer_amount > self.money:
print("余额不足,无法进行转账操作。")
return action
transfer_success, new_balance = update_balance(transfer_username, transfer_amount)
if transfer_success:
self.money -= transfer_amount
print(f"已成功向用户 {transfer_username} 转账 {transfer_amount} 元,其当前余额为 {new_balance} 元,当前账户余额为%.2f元" % self.money)
sql = "UPDATE user SET balance = %s WHERE username = %s"
con_mysql(sql, (self.money, self.username))
self.voucher(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), action, transfer_amount)
else:
print(f"用户 {transfer_username} 不存在,转账失败,不生成凭证。")
elif action == 4:
self.update()
self.voucher(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), action)
return action
def voucher(self, end_time, action, transfer_amount=None):
if transfer_amount is None:
transfer_amount = self.number
str_action = """用户:%s
操作:%s
操作金额:%s
登陆时间:%s
结束时间:%s
""" % (self.username, action_dict[action], transfer_amount, self.start_time, end_time)
with open("%s.txt" % (self.username), 'w') as f:
try:
f.write(str_action)
except Exception as e:
print("凭证打印失败,请联系管理员")
print("打印成功,请收好您的凭证")
def login():
"""
用户登录检测
:param username:用户账号
:param pwd:用户密码
:return:
"""
username = input("请输入您的账号:")
print("输入的账号是:", username)
pwd = input("请输入您的密码:")
sql = "SELECT username, pwd, balance FROM user WHERE username = %s"
result = con_mysql(sql, (username,))
if result:
if result[1] == pwd:
user_account = Account(result[0], result[2])
return user_account
else:
print("账号或密码错误")
else:
print("账号不存在")
def welcome():
print('*' * 30)
print("%s%29s" % ("*", "*"))
print("%s 欢迎进入资金管理系统 %6s" % ("*", "*"))
print("%s%29s" % ("*", "*"))
print('*' * 30)
def consume_time(func):
def inner(*args, **kwargs):
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("本次登录时间%s" % (start_time))
result = func(*args, **kwargs)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("登出时间%s" % (end_time))
return result, start_time, end_time
return inner
@consume_time
def run(user_account):
welcome()
action = user_account.implement()
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
UPDATE user SET balance = %s, start_time = %s, end_time = %s WHERE username = %s
"""
con_mysql(sql, (user_account.money, user_account.start_time, end_time, user_account.username))
return user_account
if __name__ == "__main__":
user_account = login()
while True:
if isinstance(user_account, Account):
break
while True:
result, start_time, end_time = run(user_account)
if result:
continue
else:
print("操作出现问题,退出系统。")
break