我尝试使用psycopg2
中的存储过程将列表中嵌套字典的值添加到表中,这是我从JSON应用程序收到的模式:
[
{
"team_id": 236,
"lineup": [
{
"player_id": 3043,
"country": {
"id": 61,
"name": "Denmark"
}
}
]
},
{
"team_id": 237,
"lineup": [
{
"player_id": 3045,
"country": {
"id": 62,
"name": "Italy"
}
}
]
}
]
我试图将玩家的country
添加到Postgres的一个表中,id
的类型为integer,name
的类型为VARCHAR
,下面是我的存储过程:
'''
CREATE PROCEDURE insert_country_by_lineups(data JSON)
AS $$
BEGIN
FOR team IN SELECT * FROM json_array_elements(data) LOOP
FOR player in SELECT * FROM json_array_elements(team->'lineup') LOOP
INSERT INTO country(id,name)
VALUES (CAST(player->'country'->>'id' AS integer), player->'country'->>'name')
ON CONFLICT DO NOTHING RETURNING id;
END LOOP;
END LOOP;
END;
$$ LANGUAGE plpgsql;
'''
但是,当我在光标上执行该过程时,我总是得到这样的结果:
loop variable of loop over rows must be a record variable or list of scalar variables
LINE 5: FOR team IN SELECT * FROM json_array_elements(data...
我哪里做错了?
1条答案
按热度按时间bsxbgnwa1#
使用json模块获取国家
id
和name
,然后使用psycopg2
到INSERT
到country
表中。