发布时间: 2019-09-16 14:28:28
对于Python基础语法和高级语法部分的综合应用,实现一个功能简单的资金管理系统。
2. 实验代码
2.1. 实验思路
使用PyMySql连接操作数据库,根据数据库内的信息进行登录判断。成功登陆后进入系统欢迎界面,同时为成功登录的用户创建一个用户对象,根据用户作出的操作执行相应的方法,并同步到数据库中。在操作结束后将此次操作打印出来(写入本地文件)。
2.2. 实验实现
步骤 1、创建数据库和数据表
创建数据库:
create database money;
创建数据表:
CREATE TABLE user(
username varchar(30) PRIMARY KEY,
pwd VARCHAR(100) NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME NOT NULL,
balance FLOAT NOT NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
**数据:
INSERT INTO user (username, pwd, start_time, end_time, balance)
VALUES ('admin','123456','2019.04.23', '2019.04.23',100.0);
INSERT INTO user (username, pwd, start_time, end_time, balance)
VALUES ('root','admin','2019.01.01', '2019.02.02',100.0);
步骤 2导入所需的库,定义操作字典
安装pymysql:pip install pymysql
import time
import sys
import pymysql
import getpass
action_dict = {1:"存款", 2:"取款", 3:"转账", 4:"修改密码", 5:'退出'}
步骤 3、数据库连接
考虑到系统中多次连接数据库,而连接数据库的语句相似性较高,所以将其封装成为一个方法。
# 定义连接数据库方法,sql为每次需要执行的数据库操作语句,
def con_mysql(sql):
try:
db = pymysql.connect("localhost", "root", "root", "money", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute(sql)
results = cursor.fetchone()# 查询一条数据
print(results)
db.commit() # 提交至数据库
except Exception as e:
db.rollback()
print("系统异常")
sys.exit()
db.close() # 关闭数据库
return results
# 测试方法:
sql = "select * from user"
con_mysql(sql)
输出结果:
图3-1数据库连接测试结果
步骤 4、定义用户类
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元" % (self.number))
# 取钱
def take(self):
if self.number > self.money:
print("余额不足")
self.money -= self.number
print("以取出%f元" % (self.number))
# 修改密码
def update(self):
pwd = getpass.getpass("请输入新密码:")
sql = "update user set pwd=%s where username=%s" % (pwd, self.username)
return sql
# 转账
def transfer(self):
user = input("请输入转账用户:")
if self.number > self.money:
print("余额不足")
return
else:
sql = "select username from user where username='%s'" % (user)
result = con_mysql(sql)
if result == None:
print("转账用户不存在")
self.number = 0
else:
return user
# 执行用户所选的操作
def implement(self, action):
if action == 5:
sys.exit()
elif action == 1:
try:
self.number = float(input("请输入存入得金额:"))
except Exception as e:
print("请输入正确的金额")
self.save()
elif action == 2:
try:
self.number = float(input("请输入取出的金额:"))
except Exception as e:
print("请输入正确的金额")
self.take()
sql = "update user set balance=%f where username=%s" % (self.number, self.username)
con_mysql(sql)
elif action == 3:
try:
self.number = float(input("请输入转账的金额:"))
except Exception as e:
print("请输入正确的金额")
User = self.transfer()
if User:
sql = "update user set balance=%f where username=%s" % (self.number, User)
con_mysql(sql)
else:
self.update()
# 打印操作后的凭证
def voucher(self, end_time, action):
str_action = """用户:%s \n操作:%s\n操作金额:%s\n登录时间:
%s\n结束时间:%s""" % (self.username, action_dict[action], self.number, 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("打印成功,请收好您的凭证")
步骤5、登陆功能
def login():
"""
用户登录检测
:param username: 用户账号
:param pwd: 用户密码
:return:
"""
username = input("请输入您的账号:")
# pwd = getpass.getpass("请输入您的密码:")# 隐藏输入的密码
pwd = input("请输入您的密码:")
# 编写SQL语句从数据库获取账号信息
sql = "select * from user where username='%s'"%(username)
result = con_mysql(sql)
if result:
if result[1] == pwd:
user_account = Account(result[0], result[4])
return user_account
else:
print("账号或密码错误")
else:
print("账号不存在")
# 测试登录功能
user_account = login()
步骤6、欢迎界面
def welcome():
print(' *'*15)
print(" %s%30s"%("*","*"))
print(" %s 欢迎进入资金管理系统 %5s"%("*","*"))
print(" %s%30s"%("*","*"))
print(' *'*15)
try:
action = input("请选择操作:1.存款 2.取款 3.转账 4.修改密码 5.退出:\n")
action = int(action)
except Exception as e:
print("warn:请输入正确的操作指令!")
return -1
if action not in action_dict:
print("warn:请执行正确的操作!")
return -1
return action
测试welcome方法:
action = welcome()
action
输出结果:
图3-3系统欢迎界面
步骤 7、定义系统启动函数
设置启动函数:
def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
update user set balance=%f,start_time='%s',end_time='%s' where username='%s'
"""%(user_account.money, user_account.start_time,end_time,user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)
步骤8、使用装饰器为系统添加计时功能
#定义装饰器:
def consume_time(func, *args, **kwargs):
def inner(*args, **kwargs):
start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("本次登录时间%s" % (start_time))
func()
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("登出时间%s" % (end_time))
return (start_time, end_time)
return inner
#给系统启动函数添加功能:
@consume_time
def run():
action = welcome()
user_account.implement(action)
end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = """
update user set balance=%f,start_time='%s',end_time='%s' where username='%s'
""" % (user_account.money, user_account.start_time, end_time, user_account.username)
con_mysql(sql)
user_account.voucher(end_time, action)
步骤 9、启动系统
if __name__ == "__main__":
while True:
if isinstance(user_account, Account):
break
while True:
run()
输出结果:
上一篇: 大数据培训_Hive 常用函数
下一篇: 9月底,华为将发布这个认证!