gpt4 book ai didi

python - psycopg2 "NULL"来自 csv 的值用于 sql 插入

转载 作者:行者123 更新时间:2023-12-01 05:09:30 26 4
gpt4 key购买 nike

我正在尝试使用 psycopg2 从 csv 文件上传一些数据。我了解 COPY 和 copy_from 命令,但就我而言,我需要使用 insert 语句,无论如何。我的问题是 csv 中具有整数值的列可以包含“NULL”。当光标尝试执行插入 postgres 返回错误:整数的输入语法无效:“NULL”psycopg2 文档说您应该使用 None 将 Null 传递到数据库,但在我的情况下,看起来我必须检查所有字段值是否等于“NULL”,如果是,则传递 None。这看起来不像正确的方法。有没有办法将“NULL”读取为 None 或将“NULL”传递给 psycopg2 而不进行任何检查。

with open('/my.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
pg_cursor.execute(
""" insert into "MyTable"("IntField")
values(%s)""", row
)
conn.commit()

最佳答案

您可以使用列表理解将 'NULL' 替换为 None:

row = [None if cell == 'NULL' else cell for cell in row]
pg_cursor.execute(
""" insert into "MyTable"("IntField")
values(%s)""", row
)

关于python - psycopg2 "NULL"来自 csv 的值用于 sql 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com