[Python] PyMySQL 라이브러리

KangHo Lee's avatar
Jun 10, 2025
[Python] PyMySQL 라이브러리
  • PyMySQL은 파이썬에서 MySQL 데이터베이스와 통신할 수 있게 해주는 라이브러리입니다.
  • MySQL 공식 클라이언트(mysql-connector-python)도 있지만, PyMySQL은 순수 파이썬으로 구현되어 있어 가볍고 설치가 간편합니다.
  • 외부 라이브러리이므로 설치 필요
pip install pymysql

1. DB와 연결

# db.py import pymysql def get_connection(): return pymysql.connect( host="localhost", user="root", passwd="root", charset="utf8", db="py_db", cursorclass=pymysql.cursors.DictCursor )
  • cusors → 쿼리문 실행을 위한 객체

2. UserRepository

import bcrypt from db import get_connection class UserRepository: # 사용자 등록 (비밀번호는 bcrypt로 암호화하여 저장) @staticmethod def insert_user(username, password, name, email, phone, admin): # 비밀번호 해싱 hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) sql = """ INSERT INTO user (username, password, name, email, phone, admin) VALUES (%s, %s, %s, %s, %s, %s) """ with get_connection() as conn: with conn.cursor() as cursor: cursor.execute(sql, ( username, hashed_pw.decode('utf-8'), # 문자열로 저장 name, email, phone, admin )) conn.commit() # username으로 검색 @staticmethod def select_user_by_username(username): sql = "SELECT * FROM user WHERE username = %s" with get_connection() as conn: with conn.cursor() as cursor: cursor.execute(sql, (username,)) return cursor.fetchall() # 이름 수정 @staticmethod def update_user_name(id, name): sql = "UPDATE user SET name = %s WHERE id = %s" with get_connection() as conn: with conn.cursor() as cursor: cursor.execute(sql, (name, id)) conn.commit() # 사용자 삭제 @staticmethod def delete_user_by_username(username): sql = "DELETE FROM user WHERE username = %s" with get_connection() as conn: with conn.cursor() as cursor: cursor.execute(sql, (username,)) conn.commit()
  • @staticmethod
    • @staticmethod는 파이썬 클래스에서 인스턴스(self)나 클래스(cls)를 사용하지 않는 메서드에 붙이는 데코레이터입니다.
    • 클래스 정의를 하지 않아도 UserRepository.select_user_by_username(username) 이런 식으로 호출 가능합니다.

3. login_user.py

from user_repository import UserRepository import bcrypt def login_user(): username = input("아이디: ") password = input("비밀번호: ") user_list = UserRepository.select_user_by_username(username) if not user_list: print("❌ 존재하지 않는 사용자입니다.") return user = user_list[0] if bcrypt.checkpw(password.encode('utf-8'), user['password'].encode('utf-8')): print(f"✅ {user['name']}님, 로그인 성공!") else: print("❌ 비밀번호가 일치하지 않습니다.")

4. register_user.py

import re from user_repository import UserRepository # 이메일 형식 검사 def is_valid_email(email): return re.match(r"^[\w\.-]+@[\w\.-]+\.\w+$", email) # username 중복 검사 def is_username_taken(username): user = UserRepository.select_user_by_username(username) return len(user) > 0 # 전화번호 형식 검사 함수 def is_valid_phone(phone): return re.fullmatch(r"010-\d{4}-\d{4}", phone) def register_user(): while True: username = input("아이디를 입력하세요: ") if not username: print("❌ 아이디는 필수입니다.") continue if is_username_taken(username): print("❌ 이미 사용 중인 아이디입니다.") continue break while True: password = input("비밀번호를 입력하세요: ") if not password: print("❌ 비밀번호는 필수입니다.") continue break while True: name = input("이름을 입력하세요: ") if not name: print("❌ 이름은 필수입니다.") continue break while True: email = input("이메일을 입력하세요: ") if not is_valid_email(email): print("❌ 이메일 형식이 올바르지 않습니다.") continue break # ✅ 전화번호 입력 while True: phone = input("전화번호를 입력하세요 (예: 010-1234-5678): ").strip() if not phone: phone = None break if not is_valid_phone(phone): print("❌ 전화번호 형식이 올바르지 않습니다. (예: 010-1234-5678)") continue break while True: admin_input = input("관리자입니까? (y/n): ").lower() if admin_input in ("y", "n"): admin = 1 if admin_input == "y" else 0 break print("❌ 'y' 또는 'n'으로 입력해주세요.") try: UserRepository.insert_user(username, password, name, email, phone, admin) print("✅ 사용자 등록이 완료되었습니다.") except Exception as e: print("❌ 사용자 등록 중 오류 발생:", e)

5. main.py

from register_user import register_user from login_user import login_user # 로그인 함수 임포트 # 메뉴 선택 while True: print("\n1. 회원가입") print("2. 로그인") print("0. 종료") choice = input("번호를 선택하세요: ") if choice == "1": register_user() elif choice == "2": login_user() elif choice == "0": print("👋 종료합니다.") break else: print("❌ 잘못된 선택입니다.")
  • 실행 시 콘솔에서 회원가입과 로그인 기능을 구현
 
Share article

devleekangho