目录
一、运行结果:
数据库操作可以看以下链接:
在命令窗口使用sql语句操作Mysql数据库_sql命令窗口怎么执行命令_敬往事一杯酒哈的博客-CSDN博客
数据库操作:
图1:数据库中的表数据
程序运行:
图1:首页界面
图2:成绩管理系统功能界面
图3:添加功能
图4:统计某课程在班级的成绩分布情况
图5:按学号查询
图6:修改学生信息界面
二、源码如下:
database.py:
import pymysql
import pandas as pd
class DataBase:
# 定义连接数据库对象和游标对象
db = None
cursor = None
# 连接数据库
def connectDatabases(self, user, password):
try:
self.db = pymysql.Connect(
user=user,
password=password,
host="localhost",
database="Student_Management_System",
port=3306,
charset="utf8"
)
self.cursor = self.db.cursor()
return True
except:
return False
# 添加学生信息
def addStudent(self, user, password, id, major, className, name, chinese, math, english, average_score,
total_score):
self.connectDatabases(self, user, password)
sql = "insert into students values(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
add_data = [id, name, chinese, math, english, average_score, total_score, major, className]
try:
self.cursor.execute(sql, add_data)
self.db.commit()
except:
self.db.rollback()
finally:
self.cursor.close()
self.db.close()
# 删除学生信息
def deleteStudent(self, user, password, id):
self.connectDatabases(self, user, password)
sql = "delete from students where id=%s"
del_data = [id]
try:
self.cursor.execute(sql, del_data)
self.db.commit()
except:
self.db.rollback()
finally:
self.cursor.close()
self.db.close()
# 查询指定学生信息
def checkStudent(self, user, password, id):
self.connectDatabases(self, user, password)
sql = "select * from students where id=%s"
sel_data = id
try:
self.cursor.execute(sql, sel_data)
result = self.cursor.fetchone()
print("学号:%s 专业:%s 班级:%s 姓名:%s 语文:%s 数学:%s 英语:%s 平均分:%s 总分:%s" % (
result[0], result[7], result[8], result[1], result[2], result[3], result[4], result[5], result[6]))
return result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8]
except:
self.db.rollback()
finally:
self.cursor.close()
self.db.close()
# 修改学生信息,学号不可修改
def modifyStudent(self, user, password, id, name, chinese, math, english, average_score, total_score):
self.connectDatabases(self, user, password)
sql = "update students set name=%s,chinese=%s,math=%s,english=%s,average_score=%s,total_score=%s where id=%s"
mod_data = [name, chinese, math, english, average_score, total_score, id]
try:
self.cursor.execute(sql, mod_data)
self.db.commit()
except:
self.db.rollback()
finally:
self.cursor.close()
self.db.close()
# 判断学号是否存在
def judgeStudent(self, user, password, id):
self.connectDatabases(self, user, password)
sql = "select * from students where id = %s"
sel_data = id
try:
self.cursor.execute(sql, sel_data)
row = self.cursor.fetchone()
if row is not None:
return True
except:
self.db.rollback()
return False
finally:
self.cursor.close()
self.db.close()
# 统计学生成绩的人数:
def countScores(self, user, password, className, course):
self.connectDatabases(self, user, password)
sql = "SELECT {} FROM students WHERE class = %s".format(course)
try:
self.cursor.execute(sql, (className,))
scores = self.cursor.fetchall()
if len(scores) == 0:
print("系统中没有学生信息,请先添加!")
else:
score_ranges = {
"0~59": 0,
"60~79": 0,
"80~89": 0,
"90~100": 0
}
for score_tuple in scores:
score = score_tuple[0] # 获取元组中的第一个元素
if 0 <= score <= 59:
score_ranges["0~59"] += 1
elif 60 <= score <= 79:
score_ranges["60~79"] += 1
elif 80 <= score <= 89:
score_ranges["80~89"] += 1
elif 90 <= score <= 100:
score_ranges["90~100"] += 1
print("课程:{} 班级:{}".format(course, className))
for range_name, count in score_ranges.items():
print("{} 分数范围的学生人数:{}".format(range_name, count))
except Exception as e:
print(e)
self.db.rollback()
self.db.close()
def sortScore(self, user, password, className, flag):
self.connectDatabases(self, user, password)
sql = "select * from students where class=%s"
try:
self.cursor.execute(sql, (className,))
students = self.cursor.fetchall()
if len(students) == 0:
print("系统中没有学生信息,请先添加!")
else:
students_list = []
for row in students:
student_info = {
"学号": row[0],
"专业": row[7],
"班级": row[8],
"姓名": row[1],
"语文": row[2],
"数学": row[3],
"英语": row[4],
"平均分": row[5],
"总分": row[6]
}
students_list.append(student_info)
if flag == '1':
students_list.sort(key=lambda k: (k.get("平均分")), reverse=True)
elif flag == '2':
students_list.sort(key=lambda k: (k.get("语文")), reverse=True)
elif flag == '3':
students_list.sort(key=lambda k: (k.get("数学")), reverse=True)
elif flag == '4':
students_list.sort(key=lambda k: (k.get("英语")), reverse=True)
# 排序
for student in students_list:
print("学号:%s 专业:%s 班级:%s 姓名:%s 语文:%s 数学:%s 英语:%s 平均分:%s 总分:%s" % (
student["学号"], student["专业"], student["班级"], student["姓名"], student["语文"], student["数学"],
student["英语"], student["平均分"], student["总分"]
))
choice = input("是否存入excel表?是:1 否:0")
if choice == '1':
df = pd.DataFrame(students_list)
fileName = input("请输入excel文件名:")
excel_file = fileName + '.xlsx'
df.to_excel(excel_file, index=False)
print(f"学生信息已导出到 {excel_file}")
else:
print("没有导入excel")
except:
self.db.rollback()
self.db.close()
def statisticsScore(self, user, password, className):
self.connectDatabases(self, user, password)
sql = "SELECT * FROM students WHERE class = %s"
try:
self.cursor.execute(sql, (className,))
students = self.cursor.fetchall()
if len(students) == 0:
print("系统中没有学生信息,请先添加!")
else:
students_list = []
for row in students:
student_info = {
"学号": row[0],
"专业": row[7],
"班级": row[8],
"姓名": row[1],
"语文": row[2],
"数学": row[3],
"英语": row[4],
"平均分": row[5],
"总分": row[6]
}
average_score = student_info["平均分"]
if average_score >= 80:
students_list.append(student_info)
print(students_list)
except Exception as e:
print(e)
self.db.rollback()
self.db.close()
# 输出学生信息
def showStudentInformation(self, user, password):
self.connectDatabases(self, user, password)
sql = "select * from students"
try:
self.cursor.execute(sql)
students = self.cursor.fetchall()
if len(students) == 0:
print("系统中没有学生信息,请先添加!")
else:
students_list = []
for row in students:
student_info = {
"学号": row[0],
"专业": row[7],
"班级": row[8],
"姓名": row[1],
"语文": row[2],
"数学": row[3],
"英语": row[4],
"平均分": row[5],
"总分": row[6]
}
print("学号:%s 专业:%s 班级:%s 姓名:%s 语文:%s 数学:%s 英语:%s 平均分:%s 总分:%s" % (
row[0], row[7], row[8], row[1], row[2], row[3], row[4], row[5], row[6]))
students_list.append(student_info)
# students_list.sort(key=lambda k: (k.get('平均分')))
# print(students_list)
except:
self.db.rollback()
self.db.close()
# 另存学生信息
def saveStudent(self, user, password):
self.connectDatabases(self, user, password)
sql = "select * from students"
try:
self.cursor.execute(sql)
result = self.cursor.fetchall()
if len(result) == 0:
print("系统中没有学生信息,请先添加!")
else:
file = open("学生信息.txt", "a")
for row in result:
file.write("学号:%s\t姓名:%s\t语文:%s\t数学:%s\t英语:%s\t平均分:%s\t总分:%s\n" % (
row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
except:
self.db.rollback()
finally:
self.cursor.close()
self.db.close()
file.close()
# 将excel导入数据库:
def importScoresFromExcel(self, user, password, excel_file):
self.connectDatabases(user, password)
try:
df = pd.read_excel(excel_file)
if "学号" not in df.columns or "姓名" not in df.columns or "班级" not in df.columns or "专业" not in df.columns or "语文" not in df.columns or "数学" not in df.columns or "英语" not in df.columns:
print("Excel表格格式不正确,请确保包含学号、姓名、班级、专业、语文、数学和英语列")
else:
for _, row in df.iterrows():
student_info = {
"学号": row["学号"],
"姓名": row["姓名"],
"班级": row["班级"],
"专业": row["专业"],
"语文": row["语文"],
"数学": row["数学"],
"英语": row["英语"],
"平均分": (row["语文"] + row["数学"] + row["英语"]) / 3,
"总分": row["语文"] + row["数学"] + row["英语"],
}
sql = "INSERT INTO students (学号, 姓名, 班级, 专业, 语文, 数学, 英语, 平均分, 总分) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
self.cursor.execute(sql, (
student_info["学号"], student_info["姓名"], student_info["班级"], student_info["专业"],
student_info["语文"], student_info["数学"], student_info["英语"],
student_info["平均分"], student_info["总分"]
))
self.db.commit()
print("成绩导入成功!")
except Exception as e:
print("成绩导入失败:", str(e))
self.db.rollback()
self.db.close()
project.py:
from database import DataBase
import colorama
import datetime
# 初始化
colorama.init()
# 获取当前时间
def getTime():
current_time = datetime.datetime.now()
current_date = current_time.strftime("%Y-%m-%d")
current_time = current_time.strftime("%H:%M:%S")
print(colorama.Fore.GREEN + "当前日期: " + current_date)
print(colorama.Fore.GREEN + "当前时间: " + current_time)
class Student(object):
# 定义用户名和密码
user = None
password = None
# 添加学生信息
def addStudent(self):
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入添加学生的界面 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
student_number = int(input(colorama.Fore.GREEN + "请输入添加的学生人数:"))
for i in range(student_number):
sno = input(colorama.Fore.GREEN + "请输入学号:")
if not DataBase.judgeStudent(DataBase, self.user, self.password, sno):
major = input(colorama.Fore.GREEN + "请输入专业:")
clas = input(colorama.Fore.GREEN + "请输入班级:")
sname = input(colorama.Fore.GREEN + "请输入姓名:")
chinese = int(input(colorama.Fore.GREEN + "请输入语文成绩:"))
math = int(input(colorama.Fore.GREEN + "请输入数学成绩:"))
english = int(input(colorama.Fore.GREEN + "请输入英语成绩:"))
average_score = (chinese + math + english) / 3
total_score = chinese + math + english
DataBase.addStudent(DataBase, self.user, self.password, sno, major, clas, sname, chinese, math,
english, average_score, total_score)
print(colorama.Fore.GREEN + "成功添加学号为【%s】的学生!" % sno)
else:
print(colorama.Fore.GREEN + "系统已存在学号为【%s】的学生信息,请勿重复添加!" % sno)
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
# 删除学生信息
def deleteStudent(self):
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入删除学生的界面 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
sno = input(colorama.Fore.GREEN + "请输入需要删除的学生学号:")
if DataBase.judgeStudent(DataBase, self.user, self.password, sno):
DataBase.deleteStudent(DataBase, self.user, self.password, sno)
print(colorama.Fore.GREEN + "成功删除学号为【%s】的学生!" % sno)
else:
print(colorama.Fore.GREEN + "系统中不存在学号为【%s】的学生,无法删除!" % sno)
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
# 实现修改学生信息时,用户不输入则学生属性不发生改变的功能
def user_input(self, message, info):
s = input(message)
if s == "":
return info
else:
return s
# 修改学生信息,学号不可修改
def modifyStudent(self):
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入修改学生信息的界面 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
sno = input(colorama.Fore.GREEN + "请输入需要修改的学生学号:")
if DataBase.judgeStudent(DataBase, self.user, self.password, sno):
sno, sname, chinese, math, english, average_score, total_score, major, clas = DataBase.checkStudent(
DataBase, self.user, self.password, sno)
sname = self.user_input(colorama.Fore.GREEN + "请输入学生的姓名:【回车不修改】", sname)
major = self.user_input(colorama.Fore.GREEN + "请输入学生的专业:【回车不修改】", major)
clas = self.user_input(colorama.Fore.GREEN + "请输入学生的班级:【回车不修改】", clas)
chinese = int(self.user_input(colorama.Fore.GREEN + "请输入学生语文成绩:【回车不修改】", chinese))
math = int(self.user_input(colorama.Fore.GREEN + "请输入学生数学成绩:【回车不修改】", math))
english = int(self.user_input(colorama.Fore.GREEN + "请输入学生英语成绩:【回车不修改】", english))
average_score = (chinese + math + english) / 3
total_score = chinese + math + english
DataBase.modifyStudent(DataBase, self.user, self.password, sno, sname, chinese, math, english,
average_score, total_score)
print(colorama.Fore.GREEN + "成功修改学号为【%s】的学生信息!" % sno)
else:
print(colorama.Fore.GREEN + "系统中不存在学号为【%s】的学生,无法修改!" % sno)
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
# 查询学生信息
def checkStudent(self):
print(colorama.Fore.GREEN + "#######################################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入查询学生信息的界面 * ▓")
print(colorama.Fore.GREEN + "#######################################################################################################")
id = input(colorama.Fore.GREEN + "请输入需要查询的学生学号:")
if DataBase.judgeStudent(DataBase, self.user, self.password, id):
DataBase.checkStudent(DataBase, self.user, self.password, id)
else:
print(colorama.Fore.GREEN + "系统中不存在学号为【%s】的学生!" % id)
print(colorama.Fore.GREEN + "########################################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "########################################################################################################")
# 输出学生信息
def showStudentsInformation(self):
print(colorama.Fore.GREEN + "#####################################################################################################")
print(colorama.Fore.GREEN + "▓ * 所有学生信息的界面 * ▓")
print(colorama.Fore.GREEN + "#####################################################################################################")
DataBase.showStudentInformation(DataBase, self.user, self.password)
print(colorama.Fore.GREEN + "####################################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "####################################################################################################")
# 保存学生信息
def saveStudent(self):
DataBase.saveStudent(DataBase, self.user, self.password)
print(colorama.Fore.GREEN + "保存成功!")
def sortScore(self):
print(
colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入学生成绩排序功能 * ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
className = input("请输入需要查找的班级排名:")
flag = input("请选择排列规则:按(1:平均分 2:语文 3:数学 4:英语)从大到小")
DataBase.sortScore(DataBase, self.user, self.password, className, flag)
print(
colorama.Fore.GREEN + "##########################################################################################")
print(
colorama.Fore.GREEN + "▓ ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
def countScores(self):
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入学生统计学生考试成绩分布界面 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
className = input("请输入需要统计的班级:")
course = input("请输入课程名称:")
DataBase.countScores(DataBase, self.user, self.password, className, course)
print(
colorama.Fore.GREEN + "##########################################################################################")
print(
colorama.Fore.GREEN + "▓ ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
def statisticsScore(self):
print(
colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入学生统计学生考试成绩对于80分界面 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
className = input("请输入需要统计的班级:")
DataBase.statisticsScore(DataBase, self.user, self.password, className)
print(
colorama.Fore.GREEN + "##########################################################################################")
print(
colorama.Fore.GREEN + "▓ ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
# 功能菜单打印
@staticmethod
def menu(self):
# os.system('cls')
getTime()
print(
colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入学生成绩管理系统 * ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + " ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆")
print(colorama.Fore.GREEN + " |◆|******|◆| |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 退出系统 请按 0 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 添加学生 请按 1 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 输出学生 请按 2 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 删除学生 请按 3 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 查询学生 请按 4 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 修改学生 请按 5 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 另存学生 请按 6 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 排序成绩 请按 7 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 统计成绩 请按 8 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| |◆|******|◆|")
print(colorama.Fore.GREEN + " ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆")
print(
colorama.Fore.GREEN + "##########################################################################################")
print(
colorama.Fore.GREEN + "▓ ▓")
print(
colorama.Fore.GREEN + "##########################################################################################")
choice = input(colorama.Fore.GREEN + "请输入功能前面的代码:")
if choice == "1":
self.addStudent()
elif choice == "2":
self.showStudentsInformation()
elif choice == "3":
self.deleteStudent()
elif choice == "4":
self.checkStudent()
elif choice == "5":
self.modifyStudent()
elif choice == "6":
self.saveStudent()
elif choice == "7":
self.sortScore()
elif choice == "8":
self.countScores()
elif choice == "9":
self.statisticsScore()
elif choice == "0":
print(colorama.Fore.GREEN + "感谢使用,欢迎下次登陆!")
exit()
else:
print(colorama.Fore.GREEN + "您输入的序号不对,请重新输入!")
# 登录界面
def main_menu(self):
getTime()
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ * 欢迎进入学生成绩管理系统 * ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + " ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆")
print(colorama.Fore.GREEN + " |◆|******|◆| |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 退出 请按 0 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| ☆ 登录 请按 1 |◆|******|◆|")
print(colorama.Fore.GREEN + " |◆|******|◆| |◆|******|◆|")
print(colorama.Fore.GREEN + " ◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆")
print(colorama.Fore.GREEN + "##########################################################################################")
print(colorama.Fore.GREEN + "▓ ▓")
print(colorama.Fore.GREEN + "##########################################################################################")
# 程序调用
def run(self):
while True:
self.main_menu()
choice = input(colorama.Fore.GREEN + "请输入您的选择:")
if choice == "1":
self.user = input(colorama.Fore.GREEN + "请输入您的用户名:")
self.password = input(colorama.Fore.GREEN + "请输入您的密码:")
if DataBase.connectDatabases(DataBase, self.user, self.password):
# print(colorama.Fore.GREEN+"登陆成功!!!")
while True:
self.menu(self)
else:
print(colorama.Fore.GREEN + "用户名或密码错误,请重新输入!")
else:
exit()
if __name__ == "__main__":
s = Student()
s.run()