首页 > 解决方案 > 将 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 函数的数组参数传递?

标签: pythonpostgresqlpsycopg2

解决方案


您需要转换为数组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)


推荐阅读