用psycopg2抛出错误

时间:2017-09-21 16:10:26

标签: python psycopg2 unnest

我有以下python脚本将数据插入psql

from psycopg2 import connect


con = connect(  """my string""")

query = """   INSERT INTO test.result_data 
              SELECT id,
                     result,
                     result1,
                     result2
              FROM unnest(%s) s(id text, result real, result real, result integer)
"""
t = [('1234jc', 0.0, 1.2123, 1), ('1234sc', 1.0, 1.74, 1)]
c = con.cursor()
c.execute(query, (t,))

抛出以下错误

psycopg2.ProgrammingError: function return row and query-specified return row do not match
DETAIL:  Returned type unknown at ordinal position 1, but query expects text.

以下是数据库中的表格结构

|---------------|-------|
|column name    | type  |
|---------------|-------|
|id             | text  |
|---------------|-------|
|result         |float8 |
|---------------|-------|
| cpr           |float8 |
|---------------|-------|
|cpr30          |float8 |
|---------------|-------|

1 个答案:

答案 0 :(得分:1)

您需要将这些数组转换为类型,因为postgres不知道如何将记录中的复合类型与列定义列表相匹配。

CREATE TYPE f AS (col1 text, col2 real, col3 real, col4 int);

SELECT * FROM
UNNEST(
  ARRAY[('1234jc', 0.0, 1.2123, 1), ('1234sc', 1.0, 1.74, 1)] :: f[]
);

在Python中

query = """ CREATE TYPE f AS (id text, result real, result1 real, result2 int); 
            INSERT INTO test.result_data

            SELECT id,
                   result,
                   result1,
                   result2
            FROM unnest(%s :: f[])
            AS s(id text, result real, result1 real, result2 integer)
"""