我正在创建一个脚本来从API获取数据并将其保存在Postgresql数据库中。
当我尝试使用id
选择一个SELECT id FROM (...)
并保存到查询中时,它将返回整个SELECT而不是id的值。
count = ("""
SELECT COUNT(name)
FROM cinema
WHERE name = %s;
""",
(cinema_name)
)
if count == 0:
query = ("""
INSERT INTO cinema
VALUES (%s, %s, %s, %s, %s);
"""
)
data = (cinema_id, cinema_name, cinema_is_active, cinema_created_at, cinema_updated_at)
cur.execute(query, data)
conn.commit()
theater_cinema_id = cinema_id
cinema_id += 1
else:
query = ("""
SELECT id
FROM cinema
WHERE name = %s;
""",
(cinema_name)
)
cinema_id = query
theater_cinema_id = cinema_id
#
我希望输出为id
,这是我从数据库中选择的整数。但这会返回整个查询。
PostgreSQL日志
2018-12-19 19:26:14.401 UTC [75] ERROR: column "cinema_id" is of type integer but expression is of type record at character 39
2018-12-19 19:26:14.401 UTC [75] HINT: You will need to rewrite or cast the expression.
2018-12-19 19:26:14.401 UTC [75] STATEMENT:
INSERT INTO theater
VALUES (5, ('
SELECT id
FROM cinema
WHERE name = %s;
', 'Cinemark'), 'Ingresso','4');
答案 0 :(得分:1)
在实际填充theater_cinema_id
之前,您应该先搜索电影院。
# Query the cinema ID
cur.execute("""
SELECT id
FROM table
WHERE name = %s;
""",
(cinema_name)
)
cinema = cur.fetchone()
# Checks if a cinema was found
if cinema:
# Cinema exists
theater_cinema_id = cinema[0]
else:
# Otherwise create the cinema
cur.execute("""
INSERT INTO cinema
VALUES (%s, %s, %s, %s, %s)
""",
(cinema_id, cinema_name, cinema_is_active, cinema_created_at, cinema_updated_at)
)
theater_cinema_id = cinema_id
cinema_id += 1
# Add any additional inserts / updates then commit towards the end
conn.commit()