You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解析CSV插入PostgreSQL遇类型错误:integer无法识别'None'

问题原因
  • 错误地将整数类型字段age、education_num转为字符串,当DataFrame中存在空值时,会生成字符串"None",而PostgreSQL的integer类型无法识别这个字符串,触发类型不匹配错误。
  • 使用dataFrame.size获取循环次数完全错误,size返回的是DataFrame所有元素的总个数(行数×列数),而非行数,这会导致循环超出实际行范围,get(i+1)取不到值时返回None,转成字符串后插入整数字段就会报错。
  • 代码未初始化数据库游标cursor,且循环单条插入的方式效率极低。
修复方案

直接替换为以下修正后的代码:

import psycopg2
import pandas as pd

url = 'https://raw.githubusercontent.com/akmand/datasets/main/adult.csv'
dataFrame = pd.read_csv(url)

# 把pandas的空值NaN转为Python的None,psycopg2会自动映射为PostgreSQL的NULL
dataFrame = dataFrame.where(pd.notnull(dataFrame), None)

try:
    with psycopg2.connect(
        host="localhost",
        user="dodle4532",
        password="1111",
        database="firstDataBase"
    ) as connection:
        with connection.cursor() as cursor:
            # 批量插入SQL语句
            insert_sql = """
                INSERT INTO "table" (age, workclass, education_num, marital_status)
                VALUES (%s, %s, %s, %s)
            """
            # 提取目标列数据,转为元组列表
            data_to_insert = list(dataFrame[['age', 'workclass', 'education_num', 'marital_status']].itertuples(index=False, name=None))
            cursor.executemany(insert_sql, data_to_insert)
            connection.commit()  # 提交事务
except psycopg2.DatabaseError as e:
    print(f"数据库错误: {e}")
关键修复点
  • 空值处理:用where方法把pandas的NaN转为Python原生None,避免生成"None"字符串,psycopg2会自动将None转换为PostgreSQL支持的NULL。
  • 避免索引错误:不再手动控制循环索引,通过itertuples直接提取目标列的所有行数据,彻底规避索引越界问题。
  • 保留字段类型:不再将整数类型字段转为字符串,保持原有数值类型,psycopg2会自动完成与PostgreSQL字段类型的匹配。
  • 批量插入优化:用executemany替代循环单条插入,大幅提升插入效率,减少数据库连接开销。
  • 游标与事务:正确初始化游标,并显式提交事务(默认with连接不会自动提交DML操作)。

内容的提问来源于stack exchange,提问作者dodle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 07:57:49