gpt4 book ai didi

python - 在psql中使用将相关数据插入到两个表中

转载 作者:行者123 更新时间:2023-11-29 14:16:57 28 4
gpt4 key购买 nike

我是新手,在尝试将相关值同时插入两个表时遇到了障碍。非常感谢您的指导来解决这个问题!

表 1(玩家):

CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);

表 2(匹配项):

CREATE TABLE matches(
player_id integer CONSTRAINT fk_links_match_player
REFERENCES players(player_id) NOT NULL,
match int NOT NULL,
match_result varchar(4) NOT NULL
);

我的功能:我希望函数将值传递给查询。我已经尝试了多种变体,包括以下但到目前为止没有成功。

def registerPlayer(name):
cur.execute("""WITH player_key AS
(INSERT INTO players(player_name) VALUES(%(name)s), {'name': name} RETURNING player_id)
INSERT INTO matches (player_id, match, match_result)
VALUES((SELECT player_key.player_id), 1, 'won') """)

最佳答案

我会这样做:

connection.begin()  # start a transaction
cur.execute("INSERT INTO players (player_name) VALUES (%(name)s) RETURNING player_id", {'name': name})
player_id = cur.fetchone()[0]
cur.execute("INSERT INTO matches (player_id, match, match_result) VALUES (%(player_id)s, 1, 'won')", {'player_id': player_id})
connection.commit()

关于python - 在psql中使用将相关数据插入到两个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748990/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com