一、实验目的

实现学生选课系统

二、实验环境

python3.6
pymysql(python连接mysql)
xlrd(操作excel)

三、程序结构

1.首先运行first_run.py:
功能:创建数据库、表等信息

2.运行seconnd_run.py:
功能: 实现学生选课

3.账号密码.xlsx:
存放学生信息(可以存班级花名册)

如:

四、数据库结构

表之间的联系

五、各表功能

student_login:存放学生账号信息(直接导入班级花名册,具体看代码)
									字段:
												s_no:学生学号,
												s_name:学生姓名,
												s_login:学生账号,
												s_pd:学生密码													
				course:存放课程信息
							字段:
										c_id:课程编号
										c_name:课程名称							
				student_class:学生选课表,存放学生选课信息
								字段:
										s_no:学生学号(设置外键与student_login表s_no连接)
										c_id:课程编号(设置外键与course表c_id连接)							
				admin_login:管理员信息表,存放管理员账号
								字段:
											a_no:  管理员编号
											a_name:  管理员姓名
											a_login:  管理员账号
											a_pd:  管理员密码

六、代码部分

first_run.py代码如下:

import pymysql
import xlrd
def create_all():
    try:
        password = input('请输入mysql密码(root用户):')
        db = pymysql.connect(host='localhost', user='root', password=password)
        cursor = db.cursor()
    except pymysql.err.operationalerror:
        print('密码输入错误!')
    else:
        try:
            sql = 'create database student charset utf8;'
            cursor.execute(sql)
        except pymysql.err.programmingerror:
            print("can't create database 'student' database exists!")
        else:
            sql0 = 'use student;'
            # 创建课程表
            sql1 = "create table course (c_id int(10) primary key auto_increment, c_name varchar ( 30 ) not null)default charset utf8;"
            # 创建学生账号表
            sql2 = "create table student_login(s_no char(10), s_name varchar(30), s_login char(20), s_pd char(20) not null, primary key(s_no)) default charset utf8;"
            # 创建学生选课表
            sql3 = "create table student_class (s_no char(10),c_id int,constraint foreign key (s_no) references student_login (s_no),constraint foreign key (c_id) references course (c_id),unique(s_no,c_id)) default charset utf8;"  # unique(s_no,c_id))联合唯一,确保选课唯一
            # 创建管理员账号表
            sql4 = "create table admin_login(a_no char(10), a_name varchar(30), a_login char(10)  unique, a_pd char(10) not null, primary key(a_no)) default charset utf8;"
            cursor.execute(sql0)
            cursor.execute(sql1)
            cursor.execute(sql2)
            cursor.execute(sql3)
            cursor.execute(sql4)
            db.commit()
            print('successful!')
def insert_student_login(db):
    def open_excel():
        try:
            book = xlrd.open_workbook("账号密码.xlsx")  # 文件名,把文件与py文件放在同一目录下
        except:
            print("open excel file failed!")
        else:
            try:
                sheet = book.sheet_by_name("sheet1")  # execl里面的sheet1
            except:
                print('no sheet1')
            else:
                print('yes')
                return sheet

    def insert_data():
        sheet = open_excel()
        cursor = db.cursor()
        for i in range(1, sheet.nrows):  # 第一行是标题名,对应表中的字段名所以应该从第二行开始,计算机以0开始计数,所以值是1
            s_no = str(sheet.cell(i, 0).value)[0:10]  # 取第i行第0列
            s_name = sheet.cell(i, 1).value  # 取第i行第1列,下面依次类推
            s_login = str(sheet.cell(i, 2).value)[0:10]
            s_pd = str(sheet.cell(i, 3).value)[0:10]
            # print(name)
            # print(data)
            # value = (name,data)
            # print(value)
            sql = "insert into student_login values('%s','%s','%s','%s')" % (s_no, s_name, s_login, s_pd)
            cursor.execute(sql)  # 执行sql语句
            db.commit()
    insert_data()
    # cursor.close()  # 关闭连接
    # db.close()#关闭数据
    print("插入成功!")


def insert_admin_login(db):
    try:
        cursor = db.cursor()
        sql = 'insert into admin_login values("1","admin","1","1")'
        cursor.execute(sql)
        db.commit()
    except:
        print('insert admin_login failed!!!')
    else:
        print('successful!')

def insert_into_course(db):
    try:
        cursor = db.cursor()
        sql = 'insert into course values(1,"高数"),(2,"大学英语");'      # 默认插入两个课程供选择
        cursor.execute(sql)
        db.commit()
    except:
        print('insert course failed!')
    else:
        print('successful!')

def main():
    create_all()
    try:
        passwd = input('请输入mysql密码:')
        db = pymysql.connect(host="localhost", user="root", passwd=passwd, db="student", charset='utf8')
    except:
        print("could not connect to mysql server!")
    else:
        insert_student_login(db)
        insert_admin_login(db)
        insert_into_course(db)

if __name__ == '__main__':
    main()

second_run.py代码如下:

import pymysql
# 创建游标函数
def get_db():
try:
passwd = input('请输入mysql密码:')
db = pymysql.connect('127.0.0.1', 'root', passwd, 'student')
except pymysql.err.operationalerror:
print('密码输入错误!go die!')
else:
return db
def get_cursor(db):
cursor = db.cursor()
return cursor
# 选择身份
def login(db, cursor):
menu_login()
i = 0
while true:
i += 1  # 设置循环,超过三次退出系统
login_select = input('请输入你的选项:')
if login_select == '1':  # 这里数字为字符串类型,记得要引号!
student_login(db, cursor)  # 跳入学生登录页面
elif login_select == '2':
admin_login(db, cursor)  # 跳入管理员登录页面
else:
print('请输入正确的选项!>>>>>>>>请擦擦眼睛再重选--*--(^_^)--*-- :')
if i >= 3:
print('goodbye了您啊!')
break
# 学生登录认证
def student_login(db,cursor):
print('           -----------------****----------^_^|-欢迎进入学生系统-|^_^----------****----------------------------      ')
l = 0
while true:
login = input('请输入你的账号:')
sql = "select * from student_login where student_login.s_login='%s'" % login
cursor.execute(sql)
login_id = cursor.fetchall()
if len(login_id) == 0:
l += 1
print('账号不存在,请重新输入:')
if l >= 3:
print()
print('账号不存在,请联系管理员申请账号!')
exit()
else:
p = 0  # 第一次错误:放在了while语句里面,导致超过三次无法退出(每次循环都会将p初始化为0)
while true:
password = input('请输入你的密码:')
sql2 = "select * from student_login where student_login.s_login='%s'and student_login.s_pd ='%s'" % (
login, password)
cursor.execute(sql2)
login_pd = cursor.fetchall()
if len(login_pd) == 0:
p += 1
print('密码错误!')
if p >= 3:
print('密码输入错误三次,goodbye了您啊!')
exit()
elif len(login_pd) != 0:
sql3 = "select s_name,s_no from student_login where s_login = '%s'; " % login
# sql4 = "select s_no from student_login where s_login = '%s';" % login
cursor.execute(sql3)
# cursor.execute(sql4)
data = cursor.fetchall()[0]
s_name = data[0]           # 姓名
s_no = data[1]             # 学号
print()
print("            -------------****----------^_^欢迎--|", s_name,
"|--进入学生选课系统^_^----------****-----------------")
# 学生系统模块
i = 0
while true:
student_select_menu()
student_select = input('请输入你的选项:')
if student_select == '1':
show_course(cursor)
elif student_select == '2':
select_course(db, cursor, s_name, s_no)
elif student_select == '3':
show_class(cursor, s_no)
# exit()
elif student_select == '4':
update_class(db, cursor, s_name, s_no)
elif student_select == '5':
print('\n您已退出登录^_^\n')
select = input('请输入 1 或 2 分别进入学生与管理员系统 or 输入 0 退出系统:')
if select == '1':
student_login(db, cursor)
elif select == '2':
admin_login(db, cursor)
elif select == '0':
exit()
else:
print('请输入正确选项!')
elif i >= 3:
print('goodbye了您啊!')
print()
break  # 重新登录学生操作,密码锁定
else:
i += 1
print('请输入正确的选项!>>>>>>>>请擦擦眼睛再重选--*--(^_^)--*-- :')
# 管理员登录认证
def admin_login(db, cursor):
print('      -------------------****----------^_^|-欢迎进入管理员系统-|^_^----------****--------------------------      ')
l = 0
while true:
login = input('请输入你的账号:')
sql = "select * from admin_login where admin_login.a_login='%s'" % login
cursor.execute(sql)
login_id = cursor.fetchall()
if len(login_id) == 0:
l += 1
print('账号不存在,请重新输入:')
if l >= 3:
print()
print('账号不存在,请联系站长申请账号!')
exit()
else:
p = 0  # 第一次错误:放在了while语句里面,导致超过三次无法退出(每次循环都会将p初始化为0)
while true:
password = input('请输入你的密码:')
sql2 = "select * from admin_login where admin_login.a_login='%s'and admin_login.a_pd ='%s'" % (
login, password)
cursor.execute(sql2)
login_pd = cursor.fetchall()
if len(login_pd) == 0:
p += 1
print('密码错误!')
if p >= 3:
print('密码输入错误三次,goodbye了您啊!')
exit()
elif len(login_pd) != 0:
sql3 = "select a_name from admin_login where a_login = '%s'; " % login
cursor.execute(sql3)
s_name = cursor.fetchall()[0][0]
print()
print("             --------------****----------^_^欢迎--|", s_name, "|--进入管理员系统^_^----------****-----------------")
# 管理员系统模块
i = 0
while true:
admin_select_menu()
admin_select = input('请输入你的选项:')
if admin_select == '1':
show_course(cursor)
# exit()
elif admin_select == '0':
delete_course(db, cursor)
elif admin_select == '2':
add_course(db, cursor)
# exit()
elif admin_select == '3':
show_studentlogin(cursor)
# exit()
elif admin_select == '4':
add_studentlogin(db, cursor)
# exit()
elif admin_select == '5':
show_adminlogin(cursor)
# exit()
elif admin_select == '6':
add_admin_login(db, cursor)
# exit()
elif admin_select == '7':
show_student_class(cursor)
elif admin_select == '8':
print('您已退出登录!\n')
select = input('请输入 1 或 2 分别进入学生与管理员系统 or 输入 0 退出系统:')
if select == '1':
student_login(db,cursor)
elif select == '2':
admin_login(db, cursor)
elif select == '0':
exit()
else:
print('请输入正确选项!')
elif i >= 3:
print('goodbye了您啊!')
print()
break  # 重新登录管理员系统操作
else:
i += 1
print('请输入正确的选项!>>>>>>>>请擦擦眼睛再重选--*--(^_^)--*-- :')
# 登录菜单栏
def menu_login():
menu_login1 = '''
-----------------------------****----------(^_^)----------****------------------------------------
|                                  欢迎登录学生选课系统                                           |
|                                      1、学生登录                                                |
|                                      2、管理员登录                                              |
|                  (请在菜单选择你的操作,选择其他无效,超过三次自动退出系统!)                  |
'''
print(menu_login1)
# 学生选课菜单栏
def student_select_menu():
menu_login = '''
|                                   1、查看当前可选课程                                           |
|                                   2、选择课程                                                   |
|                                   3、查看已选课程                                               |
|                                   4、更改课程                                                   |
|                                   5、退出系统                                                   |
|                  (请在菜单选择你的操作,选择其他无效,超过三次自动退出系统!)                  |
'''
print(menu_login)
# 管理员操作菜单
def admin_select_menu():
menu_login = '''
|                                  0、删除课程                                                    |
|                                  1、查看所有课程                                                |
|                                  2、添加课程                                                    |
|                                  3、查看所有学生账号信息                                        |
|                                  4、添加学生账号                                                |
|                                  5、查看所有管理员信息                                          |
|                                  6、添加管理员账号                                              |
|                                  7、查看所有学生选课信息                                        |
|                                  8、退出系统                                                    |
|                  (请在菜单选择你的操作,选择其他无效,超过三次自动退出系统!)                  |
'''
print(menu_login)
# 学生系统模块
# 查看所有课程 完
def show_course(cursor):
sql = "select * from course;"
cursor.execute(sql)
data = cursor.fetchall()
# print(type(data))       # 元组类型
item = len(data)
if item == 0:
print('暂无课程信息!')
else:
print()       # 换行
print('         课程如下:')
for i in range(item):
course = data[i]
select = {
"编号": course[0],
"课程": course[1]
}
print('                 ', select)
# 选课  完成
def select_course(db, cursor, s_name, s_no):
print(s_name)
try:
number = int(input('请输入你的课程编号:'))
sql = "select c_name from course where c_id = %s" % number  # 查找课程名字
cursor.execute(sql)
course = cursor.fetchall()[0][0]
except indexerror:
print('没有你要选的课程,请重选!')
except valueerror:
print('请正确输入课程编号!')
else:
print('你选的课程为:', course)
confirm = input('是否继续(y/n):')
if confirm == 'y' or confirm == 'y':
try:
sql_insert = "insert into student_class values('%s','%s');" % (s_no, number)     # 插入课程
cursor.execute(sql_insert)
db.commit()
except:
print("课程已存在或选课失败!")
else:
print('successful!')
else:
print('failed!!')
# 查看已选课
def show_class(cursor, s_no):
try:
sql = 'select c_name from student_class sc inner join course c on sc.c_id = c.c_id inner join student_login sl on sc.s_no = sl.s_no where sc.s_no = "%s";' % s_no
cursor.execute(sql)
data = cursor.fetchall()
except indexerror:
print('暂无选课信息!')
else:
print('\n                你选的课程为:')
for i in range(len(data)):
print('                             ', data[i][0], '^_^')
# 修改选课
def update_class(db, cursor, s_name, s_no):
while true:
try:
course = input('请输入你要修改的课程编号:')
sql0 = "select * from student_class where s_no = '%s' and c_id = '%s'" % (s_no, course)
cursor.execute(sql0)
data0 = cursor.fetchall()
if len(data0) != 0:
re_course = input('请输入你要选的课程编号:')
sql = "select c_name from course where c_id = %s" % re_course  # 查找是否存在课程编号
cursor.execute(sql)
data = cursor.fetchall()      # 课程编号所对应课程
else:
print('你没有选择这个课程!')              # 选课表中学生没有选择该课程
continue            # 终止后面语句,进入下次循环
except indexerror:
print('没有你要选的课程,请重选!')
else:
if len(data) != 0:
print('你重选的课程为:', data[0][0])     # data[0][0] 切片出来课程名称
confirm = input('是否继续(y/y):')
if confirm == 'y' or confirm == 'y':
try:
sql = "update `student`.`student_class` set `c_id` = '%s' where `s_no` = '%s' and `c_id` = '%s' limit 1" % (
re_course, s_no, course)  # 更新课程
cursor.execute(sql)
db.commit()
except:
print("失败")
else:
print('successful!')
break                    # 修改成功退出循环
else:
print('failed!!')
else:
print('没有这个课程!')
# 管理员模块
# 添加课程
def delete_course(db, cursor):
try:
course = input('请输入你要删除的课程编号:')
sql = 'delete from course where c_id = %s ' % course
cursor.execute(sql)
db.commit()
except:
print('删除失败!')
else:
print('删除成功 ^_^')
def add_course(db, cursor):
course = input('请输入你要插入的课程:')
try:
sql = "insert into course(c_name) values ('%s')" % course
cursor.execute(sql)
db.commit()  # 执行插入语句
except pymysql.err.integrityerror:
print('课程已经存在,不能重复!')
else:
print('添加成功')
# 查看学生账号  (已完成)
def show_studentlogin(cursor):
sql = 'select * from student_login;'
cursor.execute(sql)
data = cursor.fetchall()
print('          学生账号如下:\n')
for i in range(len(data)):
item = data[i]
dict = {
'sno': item[0],
's_name': item[1],
's_login': item[2],
's_pd': item[3]
}
print('                ', dict)
# 添加学生账号
def add_studentlogin(db, cursor):
try:
s_no = input('请输入学生的学号:')
s_name = input('请输入学生的姓名:')
s_login = input('请输入学生的账号:')
s_pd = input('请输入学生的密码:')
cursor.execute('insert into student_login values("%s","%s","%s","%s");'% (s_no, s_name, s_login, s_pd))
db.commit()
except pymysql.err.integrityerror:
print('添加失败,学号/账号已存在!')
else:
print('添加成功^_^')
# 查看管理员账号 完
def show_adminlogin(cursor):
sql = 'select * from admin_login;'
cursor.execute(sql)
data = cursor.fetchall()
for i in range(len(data)):
item = data[i]
dict = {
'sno': item[0],
's_name': item[1],
's_login': item[2],
's_pd': item[3]
}
print('                                 ', dict)
def add_admin_login(db, cursor):     # 注意,传入参数的时候一定要先传db再传游标
try:
s_no = input('请输入管理员的编号:')
s_name = input('请输入管理员的姓名:')
s_login = input('请输入管理员的账号:')
s_pd = input('请输入管理员的密码:')
sql = 'insert into admin_login values("%s","%s","%s","%s");' % (s_no, s_name, s_login, s_pd)
cursor.execute(sql)
db.commit()
except pymysql.err.integrityerror:
print('添加失败,编号/账号已存在!')
else:
print('添加成功^_^')
# 查看学生选课信息 (完)
def show_student_class(cursor):
sql = 'select * from student_class sc inner join course c on sc.c_id = c.c_id inner join student_login sl on sc.s_no = sl.s_no order by s_name;'
cursor.execute(sql)
data = cursor.fetchall()
print('\n')
if len(data) > 1:
for i in range(len(data)):
item = data[i]
# print(item)        # 打印查询结果
dict = {                # 取值
'sc_no': item[0],
'sc_name': item[5],
'sc_course': item[3]
}
print('                        ', dict)
else:
print('没有选课信息')
def main():
try:
db = get_db()
cursor = get_cursor(db)
except attributeerror:
print('attributeerror!')
else:
login(db, cursor)
if __name__ == '__main__':
main()

七、效果展示

运行first_run:

这里因为我已经创建过数据库,try语句直接捕获错误
删除student数据库后重新运行(亦可在sql语句中加入判断是否存在数据库)

这时可见我们的数据库及表等信息已经创建完成
可以看下数据库确认一下:

接着运行second_run:

1.学生登录

具体的功能请自行查看。

当然代码有很多不足的地方:

没有封装成类,全部代码均为函数嵌套式的,层次不是特别鲜明

没有可视化的界面,可以添加tkinter模块增加有好的可视化界面。

到此这篇关于python实战之实现简易的学生选课系统的文章就介绍到这了,更多相关python学生选课系统内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!