Python 실전 실현 간단 한 학생 수강 신청 시스템
학생 수강 신청 시스템 을 실현 하 다.
실험 환경
Python3.6
pymysql(Python 연결 MySQL)
xlrd(조작 엑셀)
3.절차 구조
1.우선 First 실행run.py:
기능:데이터베이스,테이블 등 정보 만 들 기
2.seconnd 실행run.py:
기능:학생 수강 신청 실현
3.계 정 비밀번호.xlsx:
학생 정보 저장(학급 명부 저장 가능)
예:
``
4.데이터베이스 구조
표 간 의 관계
각 표 기능
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('
^_^
')
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(' !
')
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('
:')
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(' :
')
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('
')
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()
7.효과 전시실행 Firstrun:
여 기 는 내 가 이미 데이터 베 이 스 를 만 들 었 기 때문에 try 문 구 는 직접 오 류 를 포착 합 니 다.
student 데이터 베 이 스 를 삭제 한 후 다시 실행(SQL 구문 에 데이터베이스 가 존재 하 는 지 판단 할 수 있 습 니 다)
이 때 우리 의 데이터베이스 와 표 등 정보 가 이미 만 들 어 졌 음 을 알 수 있 습 니 다.
데이터 베 이 스 를 보고 확인 할 수 있 습 니 다.
이어서 second 실행run:
1.학생 등록
구체 적 인 기능 은 스스로 확인 하 세 요.
물론 코드 가 부족 한 점 이 많 습 니 다.
클래스 로 패 키 징 되 지 않 았 습 니 다.모든 코드 는 함수 패 키 징 식 이 고 차원 이 선명 하지 않 습 니 다.
시각 화 된 인터페이스 가 없 으 면 tkinter 모듈 을 추가 하여 좋 은 시각 화 인터페이스 를 추가 할 수 있 습 니 다.
파 이 썬 실전 의 실현 에 관 한 간단 하고 쉬 운 학생 수강 신청 시스템 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 파 이 썬 학생 수강 신청 시스템 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 응원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.