버튼 수집상

[Python] pymssql INSERT 할 때 중복값 체크해서 업데이트하기 본문

TIL - Python

[Python] pymssql INSERT 할 때 중복값 체크해서 업데이트하기

cocokaribou 2023. 5. 23. 10:28

웹 크롤러에서 추출한 이미지 패스값을 저장하는데

이미지 패스가 중복될 경우, 수정한 사용자 ID만 업데이트하고

중복되지 않을 경우엔 이미지 패스와 저장한 사용자 ID를 저장하는 쿼리를 짰다.

db = pymysql.connect(host='0.0.0.0',
                     port=8000,
                     user='userName',
                     password='****',
                     db='crawler',
                     charset='utf8')
cur = db.cursor()

#...

for path in paths:
    insert_dict = {'crawler_idx': 0, 'insertUser': userId, 'updateUser': userId, 'imgPath': path}

    # 이미지 저장하거나 덮어쓸 인덱스
    # @position 변수할당
    var_sql = f"""
        SET @position := (SELECT idx FROM m_img_list
                        WHERE imgPath = {imagePath} AND insertUser = {insertUser};
    """
    cur.execute(var_sql, insert_dict)

    # idx(PK)가 중복일 때 updateUser, updateDate 칼럼만 업데이트
    insert_sql = f"""
        INSERT INTO m_img_list(idx, crawler_idx, insertUser, imgPath)
        VALUES (@position, {crawlerIdx}, {insertUser}, {imgPath})
        ON DUPLICATE KEY UPDATE updateUser = {updateUser}, updateDate = now();
    """
    cur.execute(insert_sql, insert_dict)

db.commit()

INSERT 쿼리에 넘겨줄 변수들을 딕셔너리, 혹은 튜플로 넘겨줄 수 있다.

add_salary = f"""
    INSERT INTO salaries (emp_no, salary, from_date, to_date)
    VALUES ({emp_no}, {salary}, {from_date}, {to_date})
"""

data_salary = {
    "emp_no" : emp_no,
    "salary" : 50000,
    "from_date" : tomorrow,
    "to_date" : date(9999, 1, 1)
}

cursor.execute(add_salary, data_salary)
db.commit()
728x90