数据库表
Python代码部分
import pymysql
class StMgmt(object):
def tips(self):
"""提示用户选择的操作"""
print("""
学生管理系统 1.0
1.查看所有信息
2.查看学生信息
3.修改学生信息
4.增加学生信息
5.退出学生系统
""")
def connect_base(self):
"""连接数据库并返回连接和游标"""
base = pymysql.connect(host='localhost', port=3306, db='miaosi', user='root', password='123456')
cursor = base.cursor()
return base, cursor
def view_all(self):
"""查询所有学生信息"""
base, cursor = self.connect_base()
try:
cursor.execute("SELECT * FROM pupildata")
back_data = cursor.fetchall()
for line in back_data:
print(line)
finally:
base.close()
def search_data(self):
"""查询学生信息"""
base, cursor = self.connect_base()
try:
user_name = input('请输入需要查找的学生姓名: ')
cursor.execute("SELECT * FROM pupildata WHERE name LIKE %s", (user_name,))
back_data = cursor.fetchall()
if back_data:
for data in back_data:
print(data)
else:
print('没有该学生!')
finally:
base.close()
def add_data(self):
"""增加学生信息"""
base, cursor = self.connect_base()
try:
user_id = int(input('请输入学号: '))
user_name = input('请输入姓名: ')
user_sex = input('请输入性别: ')
user_age = int(input('请输入年龄: '))
user_birthday = input('请输入生日(xxxx-xx-xx): ')
user_phone = int(input('请输入手机号: '))
user_address = input('请输入地址: ')
cursor.execute(
"INSERT INTO pupildata VALUES (%s, %s, %s, %s, %s, %s, %s)",
(user_id, user_name, user_sex, user_age, user_birthday, user_phone, user_address)
)
base.commit()
self.search_data(user_name)
print('学生数据添加成功!')
finally:
base.close()
def edit_data(self):
"""修改学生信息"""
base, cursor = self.connect_base()
try:
tips = input('请输入要修改的学生姓名: ')
# 获取用户输入的新数据
user_id = int(input('请输入学号: '))
user_name = input('请输入姓名: ')
user_sex = input('请输入性别: ')
user_age = int(input('请输入年龄: '))
user_birthday = input('请输入生日(xxxx-xx-xx): ')
user_phone = int(input('请输入手机号: '))
user_address = input('请输入地址: ')
# 修改数据
cursor.execute(
"UPDATE pupildata SET id=%s, name=%s, sex=%s, age=%s, birthday=%s, phone=%s, address=%s WHERE name = %s",
(user_id, user_name, user_sex, user_age, user_birthday, user_phone, user_address)
)
base.commit()
print('学生数据修改成功!')
finally:
base.close()
if __name__ == '__main__':
miaows = StMgmt()
miaows.tips()
while True:
try:
num = int(input('请输入你的选项: '))
if num == 1:
miaows.view_all()
elif num == 2:
miaows.search_data()
elif num == 3:
miaows.edit_data()
elif num == 4:
miaows.add_data()
elif num == 5:
print('成功退出系统!')
break
else:
print('无效的选项,请重新输入。')
except ValueError:
print('输入错误,请输入一个整数。')
except Exception as e:
print(f'发生错误:{e}')