🐍 Python + PyMySQL로 MySQL 고객 정보 다루기
이번 포스팅에서는 PyMySQL을 활용하여 MySQL 데이터베이스에 "고객 정보"를 추가하고, 수정하고, 삭제하는 기본적인 CRUD 작업 예제를 함께 정리해봅니다! 📦
✅ 1. PyMySQL 연결 설정
먼저 MySQL 데이터베이스에 연결합니다. 이 예제는 classicmodels라는 데이터베이스를 사용합니다.
import pymysql
# (1) DB 연결
connection = pymysql.connect(
host='localhost',
user='root',
password='7722',
db='classicmodels',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor # ✅ DictCursor 설정으로 결과를 딕셔너리로 반환
)
✏️ 2. 고객 추가 함수 (INSERT INTO)
def add_customer():
try:
cursor = connection.cursor()
name = "Sang In"
familiy_name = "Lee"
customerNumber = 100334
sql = """
INSERT INTO customers (
customerNumber, customerName, contactLastName, contactFirstName,
phone, addressLine1, city, country, creditLimit
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
values = (
customerNumber, "Sang In Company", familiy_name, name,
"010-1234-5678", "123 Street", "Seoul", "South Korea", 50000.00
)
cursor.execute(sql, values)
connection.commit()
print("✅ 고객 추가 완료!")
except Exception as e:
print("❌ 오류 발생:", e)
finally:
cursor.close()
# add_customer() # 👈 주석 해제 시 실행 가능
📌 Tip: 중복된 customerNumber로 삽입 시 오류 발생 가능. 기본키 중복 확인 필요!
🔄 3. 고객 정보 수정 (UPDATE)
def update_customer():
cursor = connection.cursor()
update_name = 'update_sangin'
contactLastName = 'update_lee'
try:
sql = "UPDATE customers SET customerName=%s, contactLastName=%s WHERE customerNumber=%s"
values = (update_name, contactLastName, 1000)
cursor.execute(sql, values)
connection.commit()
print("✅ 고객 정보 업데이트 완료!")
except Exception as e:
print("❌ 오류 발생:", e)
finally:
cursor.close()
# update_customer() # 👈 주석 해제 시 실행 가능
🧠 참고: WHERE 조건을 정확히 명시하지 않으면 전체 데이터가 변경될 수 있으므로 주의!
🗑️ 4. 고객 정보 삭제 (DELETE)
def delete_customer():
cursor = connection.cursor()
sql = "DELETE FROM customers WHERE customerNumber = 9999"
try:
cursor.execute(sql)
connection.commit()
print("🗑️ 고객 삭제 완료!")
except Exception as e:
print("❌ 삭제 중 오류:", e)
finally:
cursor.close()
# delete_customer() # 👈 주석 해제 시 실행 가능
🔚 마무리
- ✅ INSERT, UPDATE, DELETE 함수로 기본적인 고객 관리 기능을 구현
- ✅ try ~ except ~ finally 구조로 오류 처리 및 자원 해제
- ✅ DictCursor로 가독성 있는 결과 출력
📌 다음에는 SELECT와 JOIN, 조건 검색, 페이징 기능까지 확장해보겠습니다!
📢 질문 또는 피드백은 댓글로 남겨주세요! 🙌
'기술블로그' 카테고리의 다른 글
📌 MySQL 테이블에서 중복된 데이터를 효과적으로 삭제하는 방법 (0) | 2025.03.25 |
---|---|
📌 MySQL 데이터베이스 정리 (with 크롤링 in Selenium, PymySQL) (0) | 2025.03.25 |
📌 크롤링 시 IndexError 예외처리 방법 (초기값은 있었지만 없을경우) (0) | 2025.03.25 |
🐍 Python + PyMySQL로 MySQL 리팩토링(2/2) (0) | 2025.03.21 |
Database - SQL에서 JOIN을 언제, 왜, 어떻게 사용할까? (0) | 2025.03.21 |