【问题标题】:cannot insert None value in postgres using psycopg2无法使用 psycopg2 在 postgres 中插入 None 值
【发布时间】:2014-02-10 00:00:02
【问题描述】:

我有一个包含 100 多列和多行的数据库(postgresql)。表格中的某些单元格是空的,我正在使用 python 编写脚本,所以 None 值被放置在空单元格中,但是当我尝试插入表格时它显示以下错误。

"  psycopg2.ProgrammingError: column "none" does not exist"

我正在使用 psycopg2 作为 python-postgres 接口............有什么建议吗??

先谢谢了……

这是我的代码:-

list1=[None if str(x)=='nan' else x for x in list1];

cursor.execute("""INSERT INTO table VALUES %s""" %list1;
);

【问题讨论】:

  • Python不需要需要使用;分号。
  • list1 是否只保留 一个 值?或者您是否尝试将其用于多次插入?

标签: python postgresql psycopg2


【解决方案1】:

不要使用% 字符串插值,而是使用SQL parameters。数据库适配器可以处理None就好了,它只需要翻译成NULL,但只有当你使用SQL参数时才会发生这种情况:

list1 = [(None,) if str(x)=='nan' else (x,) for x in list1]

cursor.executemany("""INSERT INTO table VALUES %s""", list1)

我假设您尝试在此处插入多行。为此,您应该使用cursor.executemany() method 并传入要插入的行列表;每一行都是一个元组,这里有一列。

如果 list1 只是 一个 值,则使用:

param = list1[0]
if str(param) == 'nan':
    param = None

cursor.execute("""INSERT INTO table VALUES %s""", (param,))

这更明确和可读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-06-13
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多