0

我有以下 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 |
|---------------|-------|
4

1 回答 1

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)
"""
于 2017-09-21T18:47:49.557 回答