使用 psycopg2.sql 将字典插入表时出现错误“无法调整类型‘dict’”

问题描述 投票:0回答:1

我有一个 postgresql 表:

create table if not exists public.test
(
    id integer,
    name varchar,
    months jsonb
);

我有一个json:

[
    {
        "id": 1,
        "name": "name_tset",
        "months": [
            {
                "month": 7,
                "year": 2024,
                "days_in_month": 29,
                "fact": "0",
            }
        ]
    },
    ...
]

当我想插入数据时,出现错误“无法适应类型'dict'”。 我知道这是因为“月”字典列表,但是如何添加代码以使其工作?不加“月”则插入表成功。

我的代码:

for d in data:
    columns_list = list(d.keys())
    insert_query = sql.SQL("INSERT INTO {schema}.{table_name} ({columns}) VALUES ({values})").format(
        schema=sql.Identifier(f'{schema}'),
        table_name=sql.Identifier(f'{table_name}'),
        columns=sql.SQL(",").join(map(sql.Identifier, columns_list)),
        values=sql.SQL(",").join(map(sql.Placeholder, columns_list))
    )
    cursor.execute(insert_query, d)

python psycopg2
1个回答
0
投票
import psycopg2
from psycopg2.extras import Json
from psycopg2 import SQL

con = psycopg2.connect(dbname='test', user='postgres', port=5432)
cur = con.cursor()

data = [
    {
        "id": 1,
        "name": "name_tset",
        "months": [
            {
                "month": 7,
                "year": 2024,
                "days_in_month": 29,
                "fact": "0",
            }
        ]
    }
]

schema = "public"
table_name = "test"

insert_query = sql.SQL("INSERT INTO {schema}.{table_name} ({columns}) VALUES ({values})").format(
        schema=sql.Identifier(schema),
        table_name=sql.Identifier(table_name),
        columns=sql.SQL(",").join(map(sql.Identifier, columns_list)),
        values=sql.SQL(",").join(map(sql.Placeholder, columns_list))
    )

for d in data:
    cur.execute(insert_query, {"id": d["id"], "name": d["name"], "months": Json(d["months"])}

con.commit()

这产生:

select * from test ;
-[ RECORD 1 ]----------------------------------------------------------
id     | 1
name   | name_tset
months | [{"fact": "0", "year": 2024, "month": 7, "days_in_month": 29}]

© www.soinside.com 2019 - 2024. All rights reserved.