Python에서 MySQL에 데이터 삽입 시 발생한 에러
# 의문 ## 같은 int type으로 선언하고 이름도 같은데 error 발생
에러 발생: (1264, "Out of range value for column 'id' at row 1")

OverflowError: Python int too large to convert to C long
mysql.connector.errors.DataError: 1264 (22003): Out of range value for column 'id' at row 1
OverflowError: value too large to fit in C long
→ MySQL에서 INT 는 4byte 범위를 넘어서면 해당 오류 발생
Python에서의 INT Type과 MySQL에서의 INT Type에 차이가 있어 삽입이 안됨.
| 언어 | MySQL | Python |
|---|---|---|
| 크기 | 4byte | 제한없음 |
| 종류 | TINYINT, SMALLINT, MEDIUMINT, BIGINT | 내부적으로는 C의 LONG 또는 PyLongObject |
| 기타 | - | Python3부터 int는 자동으로 long으로 확장됨 |
BIGINT 로 type 변경 혹은 Python 에서 값의 범위 제한str type으로 선언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;
