ABOUT ME

IT와 컴퓨터 관련 팁, 파이썬 등과 아파트 정보, 일상적인 경험 등의 생활 정보를 정리해서 올리는 개인 블로그

  • 파이썬 도서관리 프로그램
    코딩 연습/코딩배우기 2024. 1. 3. 09:07

    파이썬 도서관리 프로그램

     

    오라클 SQL 연습을 위한 파이썬 도서관리 프로그램 코딩 연습 코드. 파이썬에서 오라클 연결 라이브러리(cx_Oracle) 호출 후 함수 기반으로  DB 쿼리한 결과를 정리한 내용입니다.

     

     

    파이썬 도서관리 프로그램 작성 개요

    VS Code 터미널 기반에서 코드를 실행하면 아래 이미지와 같이 출력되며, 메뉴를 선택하고 나오는 문구대로 입력하면 결과를 볼 수 있음

    프로그램 실행 화면
    프로그램 실행 화면

     

    코드를 실행하면,

    '도서 조회 프로그램' 메뉴 선택 목록(전체 조회, 도서 검색, 도서 추가, 도서 삭제, 프로그램 종료)이 나오고,

    번호를 선택하면 각 코드가 실행됨

     

    도서 관리 프로그램에서 사용하는 DB 테이블은 2개(book_store, book_list)로 각 컬럼은 다음과 같음 

    • book_store : 관리코드(PK), 출판사명, 전화번호, 국가, 주소
    • book_list : 도서관리코드(PK), 책 제목, 저자, 출판일자, 출판사코드(FK), 도서 가격 

    오라클 DB 관리 툴 - book_store Table
    오라클 DB 관리 툴 - book_store Table

     

    아래 다운로드 파일은 위 이미지에 있는 BOOK_STORE 관리 예제 데이터임

     

     

    1_book_store.sql
    0.00MB

     

    오라클 DB 관리 툴 - book_list Table
    오라클 DB 관리 툴 - book_list Table

     

    아래 파일은 위 이미지에 있는 BOOK_LIST 관리 예제 데이터임

    2_book_list.sql
    0.01MB

     

     

     

    IT, 전자제품 선물

     

     

    도서관리 프로그램 소스 코드

    아래 소스 코드 기반으로 프로그램 실행

    #pip install cx_oracle (or anaconda인 경우, conda install cx_oracle)
    import cx_Oracle as oci
    
    dsn = oci.makedsn('localhost', '1521', 'xe')
    conn = oci.connect('scott', 'tiger', dsn)
    # conn =  oci.connect('scott/tiger@localhost:1521/xe')  # 위 2줄 대신에 1줄로 처리 시
    cursor = conn.cursor()
    
    
    def select_all_book():
        query = ''' 
            select *
            from book_list
            join book_store
            on book_list.publisher = book_store.bscode
            order by book_list.title '''
        cursor.execute(query)
        res = cursor.fetchall()
        return res
    
    
    def select_book(book_name):
        query = f''' 
            select *
            from book_list
            join book_store
            on book_list.publisher = book_store.bscode
            where book_list.title like '%{book_name}%'
            or book_store.name like '%{book_name}%'
            order by book_list.title '''
        cursor.execute(query)
        res = cursor.fetchall()
        return res
    
    
    def insert_bstore(**kwargs):
        try:
            query = '''
                insert into book_store
                values (:1, :2, :3, :4, :5)
                '''
            cursor.execute(query, kwargs)
            conn.commit()
            return True
        except:
            return False
    
    
    def insert_book(**kwargs):
        try:
            query = '''
                insert into book_list
                values (:bcode, :title, :author, :year_of_publication, :publisher, :price)
                '''
            cursor.execute(query, kwargs)
            conn.commit()
            return True
        except:
            return False
    
    
    def delete_book(bcode):
        try:
            query = f'''
                delete book_list
                whrere bcode = {bcode}
                '''
            cursor.execute(query)
            conn.commit()
            return True
        except:
            return False
    
    
    ## 도서 조회 순환문
    while True:
        print(f'\n{"#"*5} 도서 조회 프로그램 {"#"*5}\n')
        print('1. 전체 조회')
        print('2. 도서 검색')
        print('3. 도서 추가')
        print('4. 도서 삭제')
        print('5. 프로그램 종료')
    
        menu_num = input('\n메뉴 선택 : ')
    
        if menu_num == '1':
            total_book = select_all_book()
            for book in total_book:
                print(book)
       
        elif menu_num == '2':
            while True:
                search_title = input('\n검색할 도서명(검색 종료: "엔터"/"q") : ')
                if not search_title or search_title.lower() == 'q':
                    break
                else:
                    search_book = select_book(search_title)
                    if not search_book:
                        print('\n검색 도서가 없습니다.\n')
                        continue
                    for book in search_book:
                        print(book)
                    
        elif menu_num == '3':
            append_book = {}
            bcode_ = input('도서관리번호: ')
            if bcode_.isdigit():
                _bcode = int(bcode_)
            else:
                print(f'\n관리번호를 잘못 입력했습니다. ^^!\n')
                continue
    
            if not _bcode:
                print(f'\n도서관리번호를 입력하지 않았습니다.\n번호 선택 후 다시 입력해주세요. ^^!\n')
                continue
            _title = input('도서 이름: ')
            _author = input('도서 저자: ')
            _publish_date = input('도서 출판일: ')
            
            # 출판사 목록을 보여주기 위해 쿼리
            cursor.execute('''select distinct name, bscode from book_store''')
            for publisher_name in cursor.fetchall():
                print(publisher_name, end=', ')
    
            print(f'\n{publisher_name}\n')
            _publisher = input('출판사 관리코드: ')
            price_ = input('도서 가격: ')
            if price_.isdigit():
                _price = int(price_)
            else:
                print(f'\n도서 가격을 잘못 입력했습니다. ^^!\n')
                continue
    
            append_book['bcode'] = _bcode
            append_book['title'] = _title
            append_book['author'] = _author
            append_book['year_of_publication'] = _publish_date
            append_book['publisher'] = _publisher
            append_book['price'] = _price
    
            res_booklist = insert_book(**append_book)
    
            if res_booklist:
                print(f'\n도서 리스트에 등록했습니다.\n')
            else:
                print(f'\n도서 리스트 등록 실패!! 다시 등록해주세요.\n')
                continue
    
        elif menu_num == '4':
            search_book_title = input('\n삭제할 도서명: ')
    
            if not search_book_title:
                print(f'\n검색어를 입력하지 않았습니다. ^^!\n')
            else:
                # 삭제할 도서 조호 목록을 보여주기 위해 쿼리
                cursor.execute(f"""select bcode, title, author from book_list where title like '%{search_book_title}%'""")
                books = cursor.fetchall()
    
                if books:
                    for book in books:
                        print(book)
                        # print(f"\n도서관리번호: {book[0]}\n제목: {book[1]}\n저자: {book[2]}\n")
                else:
                    print(f'\n검색 도서가 없습니다!! 다시 검색해주세요.\n')
                    continue
                
                del_bcode = input("\n삭제할 '도서 관리번호'는..? : ")
                res_delete = delete_book(del_bcode)
    
                if res_delete:
                    print(f'\n도서를 삭제했습니다.\n')
                else:
                    print(f'\n도서 삭제 실패!! 다시 삭제해주세요.\n')
                    continue
                    
        elif menu_num == '5':
            print('\n프로그램을 종료합니다.\n')
            break
    
        elif menu_num not in ('1', '2', '3', '4', '5'):
            print('\n잘못 입력하셨습니다. 다시 입력하세요!!')
    
    cursor.close()
    conn.close()

     

Designed by goodthings4me.