본문 바로가기
내가 보는 개발 공부/Python

엑셀 데이터와 db 데이터 비교해서 업데이트하기

by JeeGAe 2025. 7. 16.

pip install pandas openpyxl pymysql 로 필요 라이브러리 설치 후

import pandas as pd
import pymysql as ms

df = pd.read_excel('trans.xlsx') # 엑셀 파일 경로
titles = df['제목'].tolist() # 엑셀 데이터 상단에 제목이라는 컬럼 있어야함

conn = ms.connect( # db 정보 입력 
    host = '',
    port = ,
    user = '',
    password = '',
    database = ''
)
i = 0
try:
    with conn.cursor() as cursor:
        
        for title in titles:
            cursor.execute('SELECT * from bbs where dbtitle = %s', (title,))
            row = cursor.fetchall()

            
            if len(row) > 1:
                print(f'중복 있는 제목 {title} 개수 : {len(row)}')
                cursor.execute('UPDATE bbs SET dbcategory = "변경" WHERE dbtitle = %s', (title,)) # 중복이 있어도 update 하면 안될때는 주석
                i += 1
            elif len(row) == 0:
                print(f'없는 제목 {title}')
            else:
                cursor.execute('UPDATE bbs SET dbcategory = "변경" WHERE dbtitle = %s', (title,))
                i += 1
    conn.commit()
finally:
    conn.close()

print(f"끝 : {i}")