Reputation: 157
I am a newbie and have hit a road block trying to insert related values into two tables simultaneously. I would appreciate your guidance to solve this!
Table 1(players):
CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);
Table 2(matches):
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
);
My function: I want the function to pass values to the query. I have tried multiple variations including the following but no luck so far.
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') """)
Upvotes: 0
Views: 1750
Reputation: 125404
Do it in a single query:
query = """
with player_key as (
insert into players(player_name)
values (%(name)s)
returning player_id
)
insert into matches (player_id, match, match_result)
select player_id, 1, 'won'
from player_key
"""
cursor.execute (query, {'name': name})
Upvotes: 1
Reputation: 94676
I'd do this way:
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()
Upvotes: 3