使用psycopg2创建表时double precision类型数据报错求助
解决psycopg2 COPY导入PostgreSQL时double precision列的空字符串错误
你的问题核心不是正负十进制数值的格式问题,而是CSV文件中存在空字符串(""),而PostgreSQL的DOUBLE PRECISION/FLOAT类型无法将空字符串解析为合法数值,错误提示已明确指出第3788行的longitude列是空字符串。
解决方案
方法1:修改copy_from命令,指定空字符串映射为NULL
PostgreSQL的COPY操作允许将特定字符串识别为NULL值,默认识别的是\N,而你的CSV里用空字符串表示空值,因此只需显式指定null='':
# Loading files into postgres database with open('combined_pfa_wls.csv') as csvFile: next(csvFile) # Skipping headers cur.copy_from(csvFile, "pfa_wls", sep=",", null='') # Commit the transaction conn.commit()
方法2:预处理CSV文件
如果不想修改代码,可以先批量处理CSV,把所有空的longitude/latitude字段替换为无引号的NULL:
import csv with open('combined_pfa_wls.csv', 'r', encoding='utf-8') as infile, open('processed_pfa_wls.csv', 'w', encoding='utf-8', newline='') as outfile: reader = csv.reader(infile) writer = csv.writer(outfile) writer.writerow(next(reader)) # 写入表头 for row in reader: # 处理longitude(第5列,索引4)和latitude(第6列,索引5) row[4] = 'NULL' if row[4] == '' else row[4] row[5] = 'NULL' if row[5] == '' else row[5] writer.writerow(row)
之后使用处理后的CSV执行导入即可。
验证步骤
- 打开CSV文件,定位到第3788行(注意你跳过了表头,实际数据行是原文件的第3789行),确认
longitude列确实是空字符串。 - 应用上述任意一种方法后重新执行导入,即可解决该错误。
内容的提问来源于stack exchange,提问作者Vanessa_C
相关产品推荐
相关产品推荐

