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

使用Python psycopg2向PostgreSQL双精度列插入空值报错求助

解决psycopg2插入double precision空值报错问题

问题核心是:CSV中的空值被解析成空字符串"",但PostgreSQL的double precision类型无法识别空字符串,需要传入对应Python的None(psycopg2会自动将其转为PostgreSQL的NULL)。

直接修改代码中处理数值列的部分,对空字符串进行转换:

import csv
import psycopg2

# 直接迭代csvreader,无需先存入列表节省内存
with open('csvtry\\states.csv', encoding='utf8') as file:
    csvreader = csv.reader(file)
    
    db = psycopg2.connect(
        user="*",
        password="*",
        host="*",
        port="5432",
        database="*"
    )
    imlec = db.cursor()
    
    postgres_insert_query = """
        INSERT INTO states (id,name,country_id,country_code,country_name,state_code,type,latitude,longitude) 
        VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
    """
    
    for row in csvreader:
        # 处理空字符串转为None
        def empty_to_none(val):
            return None if val.strip() == "" else val
        
        id = row[0]
        name = row[1]
        country_id = row[2]
        country_code = row[3]
        country_name = row[4]
        state_code = row[5]
        type = row[6]
        latitude = empty_to_none(row[7])
        longitude = empty_to_none(row[8])
        
        values = (id,name,country_id,country_code,country_name,state_code,type,latitude,longitude)
        imlec.execute(postgres_insert_query, values)
    
    # 批量提交,比每次循环提交更高效
    db.commit()
    db.close()

关键修改点:

  • 新增empty_to_none函数,将空字符串(包括仅含空白的字符串)转为None
  • 对latitude和longitude这两个double precision列应用该转换
  • 优化代码:使用with语句管理文件自动关闭,批量提交事务提升效率

如果你的country_id等其他数值列也存在空值情况,同样可以用这个函数处理。

内容的提问来源于stack exchange,提问作者Selimhan Baltaş

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:45:32