Tiny Bunny

Rookies/인프라 활용을 위한 파이썬

[SK shieldus Rookies 19기] CLI 기반 CRUD 프로그램 실습

bento 2024. 3. 8. 13:44
[SK쉴더스 Rookies 19기] 클라우드 기반 스마트 융합보안 과정

01. CLI 기반 CRUD 프로그램?

CLI: 명령줄 인터페이스(Command-Line Interface 또는 Character User Interface), 글자를 입력하여 컴퓨터에 명령을 내리는 방식

CRUD: 대부분의 컴퓨터 소프트웨어가 가지는 기본적인 데이터 처리 기능인 Create(생성), Read(읽기), Update(갱신), Delete(삭제)를 묶어서 일컫는 말

 

02. 기능

회원 등록

회원 조회 → 상세 조회

상세 조회 → 수정/삭제/돌아가기

 

03. 코드

import pymysql
import re

def first_menu():                                                           
    print("==========================")
    print("메뉴")
    print("--------------------------")
    print("Q : 프로그램 종료")
    print("I : 회원 등록")
    print("S : 회원 검색")
    print("==========================")


def new_member():                                                           
    print("==========================")
    print("회원 등록")
    print("--------------------------")
    
    name = input("이름 : ")
    age = input("나이 : ")
    email = input("이메일 : ")

    name_pattern = r'^[가-힣\s]+$'                                          
    age_pattern = r'^[1-9][0-9]*$'
    email_pattern = r'^[a-zA-Z0-9+-._]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'

    if not re.match(name_pattern, name):
        print("올바른 이름 형식이 아닙니다.")
        return
    if not re.match(age_pattern, age):
        print("올바른 나이 형식이 아닙니다.")
        return
    if not re.match(email_pattern, email):
        print("올바른 이메일 형식이 아닙니다.")
        return

    try:
        with pymysql.connect(host="localhost", port=3306, user="###", password="###", db="###") as conn:
            with conn.cursor() as cursor:
                choice = input("""
==========================
Y : 등록 / N : 취소 """).upper()
                if choice == 'Y':
                    cursor.execute("INSERT INTO members (member_name, member_age, member_email) VALUES (%s, %s, %s)", (name, age, email))
                    conn.commit() 
                    print("등록했습니다.")
                    print("메뉴로 이동합니다.")
                else:
                    print("회원 등록을 취소합니다.")
                    print("메뉴로 이동합니다.")
    except pymysql.MySQLError as e:
        print(e)


def search_member():                                                        
    print("==========================")
    print("회원 검색")
    print("--------------------------")
    name = input("이름 : ")
    try:
        with pymysql.connect(host="localhost", port=3306, user="springboot", password="p@ssw0rd", db="sampledb", cursorclass=pymysql.cursors.DictCursor) as connection:
            query = "SELECT member_id, member_name FROM members WHERE member_name LIKE %s"
            cursor = connection.cursor()
            cursor.execute(query, ('%' + name + '%'))
            search_results = cursor.fetchall()
            if search_results:
                print("==========================")
                print(f"회원 검색 결과 ({len(search_results)}건)")
                print("--------------------------")
                for member in search_results:
                    print(f"{member['member_id']} : {member['member_name']}")
                print("==========================")
                choice = input("회원 번호를 입력하세요 (N: 취소) : ")
                if choice.upper() == 'N':
                    print("회원 검색이 취소되었습니다.")
                else:
                    view_member_details(choice)
            else:
                print("일치하는 결과 없음")
    except pymysql.MySQLError as e:
        print(e)


def view_member_details(member_id):                                         
    try:
        with pymysql.connect(host="localhost", port=3306, user="###", password="###", db="###", cursorclass=pymysql.cursors.DictCursor) as connection:
            query = "SELECT * FROM members WHERE member_id = %s"
            cursor = connection.cursor()
            cursor.execute(query, (member_id,))
            member = cursor.fetchone()
            if member:
                print("==========================")
                print("회원 상세 조회")
                print("--------------------------")
                print(f"아이디: {member['member_id']}")
                print(f"이름: {member['member_name']}")
                print(f"나이: {member['member_age']}")
                print(f"이메일: {member['member_email']}")
                print("==========================")
                
                udn = input("U : 수정 / D : 삭제 / N : 메뉴로 이동 : ").upper() 
                if udn == "U":
                    update_member(member_id)
                elif udn == "D":
                    delete_member(member_id)
                elif udn == "N":
                    print("메뉴로 이동합니다.")
                else:
                    print("잘못된 입력입니다. 메뉴로 이동합니다.")
    except pymysql.MySQLError as e:
        print(e)


def update_member(id):                                                          
    try:
        with pymysql.connect(host="localhost", port=3306, user="###", password="###", db="###", cursorclass=pymysql.cursors.DictCursor) as connection:
            query = "select * from members where member_id like %s"
            cursor = connection.cursor()
            cursor.execute(query, (id,))
            member = cursor.fetchone()

            print("==========================")
            print("회원 정보 수정")
            print("--------------------------")
            print(f"ID: {member['member_id']}")
            print(f"이름: {member['member_name']}")
            print(f"나이: {member['member_age']}")
            print(f"이메일: {member['member_email']}")
            print("==========================")

            age = int(input("변경할 나이 : "))
            email = input("변경할 이메일 : ")

            age_pattern = r'^[1-9][0-9]*$'
            email_pattern = r'^[a-zA-Z0-9+-._]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'

            if not re.match(age_pattern, str(age)):
                print("올바른 나이 형식이 아닙니다.")
                return
            if not re.match(email_pattern, email):
                print("올바른 이메일 형식이 아닙니다.")
                return

            yn = input("회원 정보를 수정하시겠습니까? (Y: 수정 / N: 취소) : ").upper()
            if yn == "N":
                print("회원 정보 수정을 취소합니다.")
                print("메뉴로 이동합니다.")
            else:
                query = "update members set member_age = %s, member_email = %s where member_id = %s"
                cursor.execute(query, (age, email, id))
                connection.commit()
                print("회원 정보를 정상적으로 수정했습니다.")
                print("메뉴로 이동합니다.")
    except pymysql.MySQLError as e:
        print(e)



def delete_member(member_id):                                                   
    try:
        yn = input("회원 정보를 삭제하시겠습니까? (Y: 삭제 / N: 취소) : ").upper()
        if yn == "N":
            print("회원 정보 삭제를 취소합니다.")
            print("메뉴로 이동합니다.")
            return
   
        with pymysql.connect(host="localhost", port=3306, user="###", password="###", db="###", autocommit=True) as connection:
            query = "delete from members where member_id = %s"
            cursor = connection.cursor()
            count = cursor.execute(query, (member_id,))
            if count == 1:
                print("회원 정보를 정상적으로 삭제했습니다.")
                print("메뉴로 이동합니다.")
            else:
                print("회원 정보를 삭제하는데 실패했습니다.")
                print("메뉴로 이동합니다.")
    except pymysql.MySQLError as e:
        print(e)



def main():                                                                     
    while True:
        first_menu()
        menu = input("메뉴를 선택하세요 >>>> ").upper()
        if menu == "Q":
            print("프로그램을 종료합니다.")
            break
        elif menu == "I":
            new_member()
        elif menu == "S":
            search_member()
        else:
            print("잘못된 입력입니다. Q, I, S 중 다시 선택하세요.")

if __name__ == "__main__":
    main()

어렵도다...

728x90