[Python / MySQL] Data Insert Error | Out of range

조선영·2025년 6월 18일

Python && SQL

목록 보기
1/2

Python에서 MySQL에 데이터 삽입 시 발생한 에러

# 의문
## 같은 int type으로 선언하고 이름도 같은데 error 발생

에러 메시지

에러 발생: (1264, "Out of range value for column 'id' at row 1")

pymysql 사용 시

OverflowError: Python int too large to convert to C long

mysql-connector-python 사용 시

mysql.connector.errors.DataError: 1264 (22003): Out of range value for column 'id' at row 1

MySQLdb 사용 시

OverflowError: value too large to fit in C long

→ MySQL에서 INT 는 4byte 범위를 넘어서면 해당 오류 발생


에러 발생 원인

Python에서의 INT Type과 MySQL에서의 INT Type에 차이가 있어 삽입이 안됨.

언어MySQLPython
크기4byte제한없음
종류TINYINT, SMALLINT, MEDIUMINT, BIGINT내부적으로는 C의
LONG 또는 PyLongObject
기타-Python3부터 int는 자동으로 long으로 확장됨


해결방안

  1. MySQL에서 BIGINT 로 type 변경 혹은 Python 에서 값의 범위 제한

내가 사용한 방법

  1. MySQL에서 str type으로 선언
  2. Python에서 str type으로 변환
df['id'] = df['id'].astype(str)             # id를 str type으로
df['asset_id'] = df['asset_id'].astype(str) # asset_id를 str type으로

[ 확인 code ]

for i in df['id']:
    print(type(i))

for i in df['asset_id']:
    print(type(i))

[ data insert code ]

for row in df.itertuples(index=False):
    # print(row)
    # 날짜 포맷팅 (문자열로 변환, datetime인지 확인)
    pub_date = row.published_date.strftime("%Y-%m-%d") if hasattr(row.published_date, 'strftime') else row.published_date
    upd_date = row.updated.strftime("%Y-%m-%d %H:%M:%S") if hasattr(row.updated, 'strftime') else row.updated

    # print(type((pub_date)))
    # print(type((upd_date)))
    
    sql = """
    INSERT INTO ny_article (uri, url, id, asset_id, source, published_date, updated, section, subsection, type)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
    """
    
    try:
        # print(values)
        mycursor.execute(sql, values)
        conn.commit()
    except Exception as e:
        print("에러 발생:", e)

[ DB 데이터 확인 ]

select * from ny_article;

profile
UX 기획도 하고 서비스 기획도 하고 PM도 하고 프론트도 하고 PL도 하는 중

0개의 댓글