공부/컴퓨터공학 (CS)

데이터베이스 pymysql + MySQL 응용 프로그램

leehe228 2021. 6. 18. 00:54
728x90
728x90

1. 시연 영상

 

2. 소스 코드

import pymysql
import os


def printMenu():
    os.system('cls')
    print("──────────────────────────────────────────────")
    print("    데이터베이스 과제 - 202011353 이호은")
    print("──────────────────────────────────────────────")
    print(" 1. 학생 등록     2. 학생 삭제     3. 학생 조회")
    print(" 4. 과목 등록     5. 과목 삭제     6. 과목 조회")
    print(" 7. 수강 신청     8. 수강 취소     9. 수강 조회\n 0. 종료")
    print(" 메뉴 선택 : ", end='')


def INSERT_STUDENT():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # STUDENT 테이블에 학생 튜플을 INSERT하기 위한 SQL문 선언
        sql = "insert into STUDENT(SNO, SNAME, SYEAR, DEPT) values (%s, %s, %s, %s)"

        # INSERT할 학생 정보를 입력 받음
        print("──────── 학생 등록 ────────")
        sno = int(input("학번 : "))
        sname = input("이름 : ")
        syear = int(input("학년 : "))
        dept = input("학과 : ")

        # 새로운 학생 튜플 생성
        newStudent = (sno, sname, syear, dept)

        # SQL문 실행
        curs.execute(sql, newStudent)
        # 데이터베이스에 적용
        conn.commit()

        print("학생 등록이 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 학생을 등록할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF INSERT_STUDENT


def DELETE_STUDENT():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # 삭제할 학생 튜플의 학번 입력 받음
        print("──────── 학생 삭제 ────────")
        sno = int(input("학번 : "))

        # STUDENT 테이블에서 특정 튜플을 DELETE하기 위한 SQL문 선언
        sql = "delete from STUDENT where SNO=%s" % (sno)

        # SQL문 실행
        curs.execute(sql)
        # 데이터베이스에 적용
        conn.commit()

        print("학생 삭제가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 학생을 삭제할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF DELETE_STUDENT


def SELECT_STUDENT():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # *가 입력되면 전체 데이터 조회, 이외는 입력값을 학번으로 가지는 데이터 조회
        print("──────── 학생 조회 ────────")
        print("전체 조회 시 * 입력, 특정 학번 조회 시 학번 입력")
        sno = input("입력 : ")

        if sno == '*':
            # STUDENT 테이블의 모든 튜플을 조회하기 위한 SQL문 선언
            sql = "select * from STUDENT"
        else:
            sno = int(sno)
            # COURSE 테이블의 학번이 sno인 튜플을 조회하기 위한 SQL문 선언
            sql = "select * from STUDENT where SNO=%s order by SNO" % (sno)

        # SQL문 실행
        curs.execute(sql)

        # 실행 결과 중 튜플 하나 가져옴
        row = curs.fetchone()

        # 튜플이 없다면 결과가 없는 것이므로
        if not row:
            print("조회된 학생이 없습니다.")

        # 조회된 튜플이 있다면
        else:
            print("┌────────────┬────────────┬──────┬──────────┐")
            print("│    학번    │    이름    │ 학년 │   학과   │")
            print("├────────────┼────────────┼──────┼──────────┤")
            # 튜플 한 개 씩 가져와 출력
            while row:
                print("│ {0:>10s} │ {1} │ {2:>4s} │ {3} │".format(str(row['SNO']), ' '*(10-2*len(
                    row['SNAME']))+row['SNAME'], str(row['SYEAR']), ' '*(8-2*len(row['DEPT']))+row['DEPT']))
                row = curs.fetchone()

            print("└────────────┴────────────┴──────┴──────────┘")
            print("학생 조회가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 학생을 조회할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF SELECT_STUDENT


def INSERT_COURSE():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # COURSE 테이블에 튜플을 INSERT하기 위한 SQL문 선언
        sql = "insert into COURSE(CNO, CNAME, CREDIT, DEPT, PRNAME) values (%s, %s, %s, %s, %s)"

        # 등록하기 위한 과목 정보 입력 받음
        print("──────── 과목 등록 ────────")
        cno = input("과목 번호 : ")
        cname = input("과목명 : ")
        credit = int(input("학점 : "))
        dept = input("학과 : ")
        prname = input("담당 교수님 : ")

        # 새로운 과목 튜플 생성
        newCourse = (cno, cname, credit, dept, prname)

        # SQL문 실행
        curs.execute(sql, newCourse)
        # 데이터베이스에 적용
        conn.commit()

        print("과목 등록이 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 과목을 등록할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF INSERT_COURSE


def DELETE_COURSE():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # 삭제하기 위한 과목의 과목 번호 입력 받음
        print("──────── 과목 삭제 ────────")
        cno = input("과목 번호 : ")

        # COURSE 테이블에서 특정 튜플을 DELETE하기 위한 SQL문 선언
        sql = "delete from COURSE where CNO='%s'" % (cno)

        # SQL문 실행
        curs.execute(sql)
        # 데이터베이스에 적용
        conn.commit()

        print("과목 삭제가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 과목을 삭제할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF DELETE_COURSE


def SELECT_COURSE():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # * 입력 시 전체 튜플 조회, 이외는 입력값을 과목 번호로 하는 튜플 조회
        print("──────── 과목 조회 ────────")
        print("전체 조회 시 * 입력, 특정 과목 번호 조회 시 과목 번호 입력")
        cno = input("입력 : ")

        if cno == '*':
            # 모든 데이터 조회를 위한 SQL문 선언
            sql = "select * from COURSE"
        else:
            # 과목번호가 cno인 튜플을 검색하기 위한 SQL문 선언
            sql = "select * from COURSE where CNO='%s' order by CNO" % (cno)

        # SQL문 실행
        curs.execute(sql)

        # 실행 결과에서 튜플 한 개 가져옴
        row = curs.fetchone()

        # 튜플이 없다면 
        if not row:
            print("조회된 과목이 없습니다.")

        else:
            print("┌──────────┬────────────────┬──────┬──────────┬────────────┐")
            print("│ 과목번호 │     과목명     │ 학점 │   학과   │ 담당교수님 │")
            print("├──────────┼────────────────┼──────┼──────────┼────────────┤")
            # 튜플을 한 개 씩 가져와 출력
            while row:
                print("│ {0:>8s} │ {1} │ {2:>4s} │ {3} │ {4} │".format(row['CNO'], ' '*(14-2*len(row['CNAME']))+row['CNAME'], str(
                    row['CREDIT']), ' '*(8-2*len(row['DEPT']))+row['DEPT'], ' '*(10-2*len(row['PRNAME']))+row['PRNAME']))
                row = curs.fetchone()

            print("└──────────┴────────────────┴──────┴──────────┴────────────┘")
            print("과목 조회가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 과목을 조회할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF SELECT_COURSE


def INSERT_ENROL():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # ENROL 테이블에 튜플을 INSERT하기 위한 SQL문 선언
        sql = "insert into ENROL(SNO, CNO) values (%s, %s)"

        # 추가할 등록(수강)의 학번과 과목 번호 입력 받음
        print("──────── 수강 신청 ────────")
        sno = int(input("학번 : "))
        cno = input("과목 번호 : ")

        # 새로운 수강 튜플 생성
        newEnrol = (sno, cno)

        # SQL문 실행
        curs.execute(sql, newEnrol)
        # 데이터베이스에 적용
        conn.commit()

        print("수강신청이 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 수강신청을 할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF INSERT_ENROL


def DELETE_ENROL():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # 삭제할 수강의 학번과 과목 번호 입력 받음
        print("──────── 수강 취소 ────────")
        sno = int(input("학번 : "))
        cno = input("과목 번호 : ")

        # ENROL 테이블에서 특정 튜플을 DELETE하기 위한 SQL문 선언
        sql = "delete from ENROL where SNO=%s and CNO='%s'" % (sno, cno)

        # SQL문 실행
        curs.execute(sql)
        # 데이터베이스에 적용
        conn.commit()

        print("수강 취소가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 수강 취소할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')

# END of DEF DELETE_ENROL


def SELECT_ENROL():
    # SQL 데이터베이스 접근하기 위해 conn, curs 인스턴스 생성
    conn = pymysql.connect(host='localhost', user='db2020',
                           password='db2020', db='university')
    curs = conn.cursor(pymysql.cursors.DictCursor)

    try:
        # 전체 조회, 학번으로 조회, 과목 번호로 조회 선택 받음
        print("──────── 수강 조회 ────────")
        print("1. 전체 조회     2. 학번으로 조회     3. 과목 번호로 조회")
        slc = int(input("메뉴 선택 : "))

        if slc == 1:
            # ENROL 테이블의 모든 튜플을 조회하기 위한 SQL문 선언
            sql = "select * from ENROL order by SNO, CNO"
        elif slc == 2:
            sno = int(input("학번 : "))
            # 학번이 sno인 튜플을 조회하기 위한 SQL문 선언
            sql = "select * from ENROL where SNO=%s order by CNO" % (sno)
        elif slc == 3:
            cno = input("과목 번호 : ")
            # 과목번호가 cno인 튜플을 조회하기 위한 SQL문 선언
            sql = "select * from ENROL where CNO='%s' order by SNO" % (cno)
        else:
            # 잘못된 입력의 경우
            print("올바른 메뉴가 아닙니다.")
            curs.close()
            conn.close()

            os.system('pause')
            return

        # SQL문 실행
        curs.execute(sql)

        # 실행 결과에서 튜플 한 개 가져옴
        row = curs.fetchone()
        
        # 조회된 튜플이 없다면
        if not row:
            print("조회된 수강이 없습니다.")

        else:
            print("┌────────────┬──────────┬──────┬──────────┬──────────┐")
            print("│    학번    │ 과목번호 │ 성적 │ 중간고사 │ 기말고사 │")
            print("├────────────┼──────────┼──────┼──────────┼──────────┤")
            # 실행 결과에서 튜플을 한 개 씩 가져와 출력
            while row:
                for k in row.keys():
                    if row[k] == None:
                        row[k] = 'NULL'

                print("│ {0:>10s} │ {1:>8s} │ {2:>4s} │ {3:>8s} │ {4:>8s} │".format(str(
                    row['SNO']), row['CNO'], row['GRADE'], str(row['MIDTERM']), str(row['FINAL'])))
                row = curs.fetchone()

            print("└────────────┴──────────┴──────┴──────────┴──────────┘")
            print("수강 조회가 완료되었습니다.")

    # 오류 발생 시 
    except Exception as e:
        print("오류 : 수강을 조회할 수 없습니다.")
        print(e)

    # curs, conn 닫음
    curs.close()
    conn.close()

    os.system('pause')


# END of DEF SELECT_ENROL


if __name__ == '__main__':

    while True:
        printMenu()
        slc = int(input())

        if slc == 1:
            INSERT_STUDENT()

        elif slc == 2:
            DELETE_STUDENT()

        elif slc == 3:
            SELECT_STUDENT()

        elif slc == 4:
            INSERT_COURSE()

        elif slc == 5:
            DELETE_COURSE()

        elif slc == 6:
            SELECT_COURSE()

        elif slc == 7:
            INSERT_ENROL()

        elif slc == 8:
            DELETE_ENROL()

        elif slc == 9:
            SELECT_ENROL()

        elif slc == 0:
            break

        else:
            print("올바른 메뉴가 아닙니다.")
            os.system('pause')
728x90
728x90