学生成绩系统(用数据库操作)源码

  • mysql_util.py
import pymysql
import traceback

#创造数据库对象
class MysqlUtil():
    def __init__(self):
        self.host = 'localhost',
        self.user = 'root',
        self.password = 'root',
        self.db = 'students',
        self.charset = 'utf8'
        self.connect()

    def connect(self):#连接数据库
        self.connection = pymysql.connect(
            host='localhost',
            user='****',#数据库用户名
            password='****',#数据库密码
            db='students',
            charset='utf8',
            cursorclass=pymysql.cursors.DictCursor#得到的结果表示为字典形式
        )

    def traceback(self):
        with open('log.txt', 'a') as file:
            traceback.print_exc(file=file)#将错误写入文件中
            file.flush()#不缓存直接写入

    def close(self):
        if getattr(self, 'connection', 0):
            self.connection.close()

    def execute(self, sql):
        try:
            with self.connection.cursor() as cursor:
                result = cursor.execute(sql)#result为结果影响条数
            self.connection.commit()
            return result
        except:
            traceback()
            self.connection.rollback()#发生错误后是操作撤销

    def find(self, sql, fetch_one = False):
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql)
            if fetch_one:
                result = cursor.fetchone()
            else:
                result = cursor.fetchall()
            return result
        except:
            traceback()

    def __del__(self):#对象执行完时会自动执行这个函数,就行__enter__()对象实例化时会自动进入这个函数
        self.close()

if __name__ == "__main__":
    db = MysqlUtil()
    sql = "select version()"
    result = db.find(sql,fetch_one=True)
    print(result)
  • run.py
from mysql_util import MysqlUtil
from beautifultable import BeautifulTable
def show_menu():
    print("---------------------------")
    print("      学生成绩管理系统 V1.0")
    print("                           ")
    print("      1:添加学生成绩信息")
    print("      2:查询学生成绩信息")
    print("      3:显示所有学生成绩信息")
    print("      4:删除学生成绩信息")
    print("      5:修改学生成绩信息")
    print("      6:总分成绩信息排名")
    print("      7:单科成绩信息排名")
    print("      8:查询单科成绩信息(最高分/最低分/平均分)")
    print("      0:退出系统")
    print("                           ")
    print("---------------------------")

def confirm():
    enter_str = input("确认请输入y,否则输入n:")
    if enter_str == 'n':
        return False
    else:
        return True


#输出为表格形式
def print_table(column_headers = None, rows_value = None):
    table = BeautifulTable()
    table.column_headers = column_headers
    if isinstance(rows_value, list):#rows_value是否有多个值
        for result in rows_value:
            table.append_row(result.values())
    else:
        table.append_row(rows_value.values())
    print(table)

#查找学生信息
def find_student_info(student_number):
    sql = f"select {fields} from student where student_number = {student_number}"
    result = db.find(sql, fetch_one=True)
    return result


def main():
    show_menu()
    while True:
        number = int(input("请输入选择:"))
        if number == 1:#添加学生成绩信息
            student_number = input("请输入学号:")
            student_name = input("请输入学生姓名:")
            chinese = input("请输入语文成绩:")
            math = input("请输入数学成绩:")
            english = input("请输入英语成绩:")
            if not confirm():
                continue
            values = (student_number, student_name, chinese, math, english)
            sql = f'insert into student({fields}) values {values}'
            result = db.execute(sql)
            result = "添加成功" if result else "添加失败"
            print(result)
        elif number == 2:#查询学生成绩信息
            student_number = input("请输入学号:")
            result = find_student_info(student_number)
            if result:
                print_table(fields.split(","), result)
            else:
                print("该学号不存在")
        elif number == 3:#显示所有学生成绩信息
            sql = f'select {fields} from student'
            result = db.find(sql)
            if result:
                print_table(fields.split(","), result)
            else:
                print("暂时没有学生信息")
        elif number == 4:#删除学生成绩信息
            student_number = input("请输入学号:")
            if not find_student_info(student_number):
                print("该学号不存在")
                continue
            if not confirm():
                continue
            sql = f'delete from student where student_number = {student_number}'
            result = db.execute(sql)
            result = "删除成功" if result else "删除失败"
            print(result)
        elif number == 5:#修改学生成绩信息
            student_number = input("请输入学号:")
            if not find_student_info(student_number):
                print("该学号不存在")
                continue
            content = input("请输入要更改的信息, 如果有多个则用逗号隔开(如chinese = 90, math = 90, english = 90):")
            if not confirm():
                continue
            sql = f'update student set {content} where student_number = {student_number}'
            result = db.execute(sql)
            result = "更改成功" if result else "更改失败"
            print(result)
        elif number == 6:#总分成绩信息排名
            total_fields = ",".join((fields, "chinese+math+english as total"))
            order_by = "total desc"
            sql = f'select {total_fields} from student order by {order_by}'
            result = db.find(sql)
            if result:
                print_table(total_fields.split(","), result)
            else:
                print("暂时没有学生信息")
        elif number == 7:#单科成绩信息排名
            subject = input("请输入要查询的科目(chinese或者math或者english):")
            sql = f"select {fields} from student order by {subject} desc"
            result = db.find(sql)
            if result:
                print_table(fields.split(","), result)
            else:
                print("暂时没有学生信息")

        elif number == 8:#查询单科成绩信息(最高分 / 最低分 / 平均分)
            subject = input("请输入要查询的科目(chinese或者math或者english):")
            sql = f"select max({subject}) as highest, min({subject}) as lowest, avg({subject}) as average from student"
            counter = "highest, lowest, average"
            result = db.find(sql, fetch_one= True)
            if result:
                print_table(counter.split(","), result)
            else:
                print("暂时没有该单科信息")
        elif number == 0:#查询学生成绩信息
            print("退出成功")
            break
        else:
            print("输入无效,请重新输入")


if __name__ == '__main__':
    fields = "student_number, student_name, chinese, math, english"
    db = MysqlUtil()
    main()

你可能感兴趣的:(python,数据库,python,database)