postgresql - 在带有 psycopg2 的 Postgresql 中找不到自定义类型
问题描述
介绍:
我正在尝试使用 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 中引用自定义类型时,需要引用创建类型的数据库以及类型。
像这样:
(%(dict_name)s)::"database_name".type
#or
CAST(%(dict_name)s as "database_name".type)
小心引用!
推荐阅读
- c# - 基本 api 控制器获取路由 c#
- algorithm - 解决具有额外约束的分区的正确算法是什么?
- c# - 为什么 Visual Studio 项目文件中需要 ProjectTypeGuids?
- amazon-web-services - 如何禁用 AWS CodeBuild 工件的加密?
- opencv - 如何将 .so 和可执行文件合并到一个 .so 文件中
- java - 如何从 RecyclerView.Adapter 的 OnBindViewHolder 中的另一个列表中提取列表
- node.js - 我们是将sailsjs嵌入reactjs还是将reactsjs嵌入sailsjs?我们怎样才能做到这一点?
- php - 如何读取 .xhprof 文件?
- javascript - 如何在节点 js 的 express-session 中的 MemoryStore 中按 id 查找和删除会话
- python - 如何使用 matplotlib 在背景图像上绘制多个子图?