【问题标题】:Custom types not found in Postgresql with psycopg2使用 psycopg2 在 Postgresql 中找不到自定义类型
【发布时间】:2020-06-23 02:19:56
【问题描述】:

简介:

我正在尝试使用 Python/psycopg2 以以下格式将数据插入 Postgres:

(integer, date, integer, customtype[], customtype[], customtype[], customtype[])

但是,当我尝试插入它们时,我总是收到此错误:

'"customtype[]" 不存在'


我的设置如何:

我有一个包含我需要的数据的字典,如下所示:

data_dict = {'integer1':1, 'date': datetime(), 
             'integer2': 2, 'custom1':[(str, double, double),(str, double, double)], 
             'custom2':[(str, double, double),(str, double, double),(str, double, double)],
             'custom3':[(str, double, double),(str, double, double),(str, double, double)],
             'custom4':[(str, double, double)]}

每个自定义数组可以根据需要拥有任意数量的自定义元组。

我已经为这些自定义元组创建了一个类型,如下所示:

"CREATE TYPE customtype AS (text, double precision, double precision)"

我创建了一个包含 customtype[] 列的表。


到目前为止我所做的尝试:

query = """INSERT INTO table (column names...) VALUES
            (%(integer1)s, %(date)s, %(integer2)s, 
            %(custom1)s::customtype[], [...]);"""

还有:

query = """INSERT INTO table (column names...) VALUES
            (%(integer1)s, %(date)s, %(integer2)s, 
            CAST(%(custom1)s AS customtype[]), [...]);"""

但两个选项呈现相同的结果。

最后一个问题:

如何使用 Psycopg2 在 Postgresql 中插入这些记录类型的数组?

也许我完全误解了 Postgresql 的工作原理。我来自 BigQuery 记录/重复类型背景。

Ps.:这就是我的查询方式:

cursor.execute(query,data_dict)

【问题讨论】:

    标签: postgresql psycopg2


    【解决方案1】:

    问题是我在数据库中创建了类型。

    在 Postgresql 中引用自定义类型时,需要引用创建类型的数据库以及类型。

    像这样:

    (%(dict_name)s)::"database_name".type
    #or
    CAST(%(dict_name)s as "database_name".type)
    

    请谨慎引用!

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 2017-10-07
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2014-08-21
      • 2017-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多