使用python实现了一个简单的学生管理系统,包含注册,登陆,修改密码和简单查询信息等简单功能,后续感兴趣可以自己添加上其他信息或与已有的学生信息表相关联。注册后存入数据库对应表格中,并对密码进行加密,表格比较简单,只有id,姓名,密码和is_delete四个字段,代码使用时其实还应该加上异常捕捉,由于代码比较简单这里就没有使用。下面上代码:
from pymysql import connect
class Userlogin(object):
def __init__(self):
self.conn = connect(host='localhost', port=3306, user='root', password='mysql',
database='students', charset='utf8')
self.cur = self.conn.cursor()
self.is_login = 0
self.login_name = ''
def __del__(self):
self.cur.close()
self.conn.close()
def reg(self):
'''用户注册'''
uname = input('请输入要注册的用户名:')
sql = '''select count(*) from users where uname = %s;'''
self.cur.execute(sql, uname)
res = self.cur.fetchall()[0][0]
print(res)
if res:
print('用户名已存在')
return
while True:
upwd = input('请输入要注册的密码:')
if not (len(upwd) >= 6 and len(upwd) <= 20):
print('密码长度需为6-20位!!!')
continue
upwd_1 = input('请再输一次:')
if upwd_1 == upwd:
break
else:
print('两次输入不一致,请重新输入!!!')
sql = '''insert into users(uname, upwd) value(%s, password(%s));'''
param = [uname, upwd]
self.cur.execute(sql, param)
self.conn.commit()
def login(self):
'''用户登陆'''
uname = input('请输入要登录的用户名:')
upwd = input('请输入密码:')
sql = '''select count(*) from users where uname = %s and upwd = password(%s) and is_delete = 0;'''
param = [uname, upwd]
self.cur.execute(sql, param)
res = self.cur.fetchall()[0][0]
if not res:
print('用户名或密码错误,请重新登陆')
else:
print('登陆成功')
self.is_login = 1
self.login_name = uname
def select(self):
'''查询所有学生'''
sql = '''select * from users where is_delete = 0;'''
self.cur.execute(sql)
table_data = self.cur.fetchall()
for data in table_data:
print(data)
def change_pwd(self):
'''更改密码'''
while True:
new_pwd = input('请输入新密码:')
if not (len(new_pwd) >= 6 and len(new_pwd) <= 20):
print('密码长度需为6-20位!!!')
continue
new_pwd1 = input('请再输一次:')
if new_pwd != new_pwd1:
print('两次输入不一致!!!')
else:
break
sql = '''update users set upwd = password(%s) where uname = %s'''
params = [new_pwd, self.login_name]
self.cur.execute(sql, params)
print('修改成功,请重新登陆')
self.is_login = 0
def logoff(self):
'''用户登出'''
if self.is_login == 0:
print('当前没有用户登陆')
return
self.is_login = 0
print('注销成功')
def run(self):
while True:
if self.is_login == 0:
print('1.注册')
print('2.登陆')
print('3.退出')
commond = input('请输入要操作的数字:')
if commond == '1':
self.reg()
elif commond == '2':
self.login()
elif commond == '3':
break
else:
print('请输入正确的操作数!!!')
elif self.is_login == 1:
print('1.查询')
print('2.修改密码')
print('3.注销登陆')
commond = input('请输入要操作的数字:')
if commond == '1':
self.select()
elif commond == '2':
self.change_pwd()
elif commond == '3':
self.logoff()
else:
print('请输入正确的指令!!!')
else:
self.is_login = 0
def main():
reglogin = Userlogin()
reglogin.run()
if __name__ == '__main__':
main()