python - 将 python 列表转换为 SQL 复合类型数组以作为参数传递给 postgreSQL 函数
问题描述
我在 postgreSQL 中有以下复合类型:
Composite type "public.type_data"
Column | Type | Modifiers
-------------+---------+-----------
series_id | text |
data_date | date |
data_value | numeric |
data_source | text |
我用来作为参数传递VARIADIC input_array type_data[]
给 postgreSQL 中的函数。我在 python 中也有以下列表:
list = [['BRLUSD', '2021-02-26', 5.5302, 'gen'], ['BRLUSD', '2021-02-25', 5.46, 'gen']]
我想作为参数传递给我的函数。我query = cur.mogrify("SELECT * FROM data_update(%s::type_data);", (list))
用来获取查询字符串,但它返回以下错误:
query = cur.mogrify("SELECT * FROM data_update(%s::type_data);", (list) )
TypeError: not all arguments converted during string formatting
我错过了什么。有没有更好的方法将列表作为 postgreSQL 函数的数组参数传递?
解决方案
您需要转换为数组type_data
而不是类型type_data
此外,内部列表应该是元组:psycopg2 将列表视为数组。
如果您需要在 Python 代码中使用 Postgresql 返回的复合类型,则register_composite函数可能很有用。
import psycopg2
with psycopg2.connect(database="test") as conn:
cur = conn.cursor()
cur.execute("""DROP FUNCTION IF EXISTS get_my_values""")
cur.execute("""DROP TYPE IF EXISTS my_type""")
conn.commit()
cur.execute(
"""CREATE TYPE my_type AS (series_id text, data_date date, data_value numeric, data_source text)"""
)
cur.execute(
"""CREATE FUNCTION get_my_values(my_type[]) RETURNS numeric AS $$
SELECT $1[1].data_value AS dv
$$ LANGUAGE SQL;"""
)
conn.commit()
data = [
(
"BRLUSD",
"2021-02-26",
5.5302,
"gen",
),
(
"BRLUSD",
"2021-02-25",
5.46,
"gen",
),
]
cur.execute("""SELECT get_my_values(%s::my_type[])""", (data,))
(result,) = cur.fetchone()
print(result)
推荐阅读
- chirp - 安卓啁啾安装12345
- html - 将第一个子默认选定颜色更改回未聚焦颜色
- fedora - EasyScreenCast 看不到网络摄像头 fedora 29
- javascript - 从要作为函数参数传递的数据库值中删除撇号
- react-native - 在 React Native 中处理低内存
- python - 如何在 Mac OS 上使用 Selenium WebDriver?
- android - Android 警报 - 键盘锁解除后,活动有时仍为黑色
- mongodb - 使用 findOneAndUpdate() 更新两个不同属性时的 MongoDB 语法
- android - 如何获取任何 WordPress 网站的所有插件和活动主题的名称?
- c# - 如何在 C# 中一次播放多个频率的声音?