I have a database and have added an additional column ‘team’ so it looks like this
date | forename | surname | team
-----------------------------------------
1/1/01 | james | smith |
2/2/02 | paul | jones |
3/3/03 | steven | bradley |
I want to add an entry to the team column from each, chosen using the random package from a list of teams
import psycopg2
import random
dbconfig = {
"dbname": "mydb",
"host": "127.0.0.1",
"user": "user",
"password": "password",
"port": 5432,
}
connection = psycopg2.connect(**dbconfig)
connection.autocommit = True
teams = ["liverpool", "chelsea", "arsenal"]
cursor = connection.cursor()
cursor.execute("select * from players")
players = cursor.fetchall()
for player in players:
team = random.choice(teams)
query = f""" update trades set team = '{team}' """
But when I do this it updates the team for every row rather than just the current one, so I get left with
date | forename | surname | team
-----------------------------------------
1/1/01 | james | smith | chelsea
2/2/02 | paul | jones | chelsea
3/3/03 | steven | bradley | chelsea
Can I update the rows one by one or in bulk using the random variable?
>Solution :
Include a WHERE clause that matches the specific row based on the date, forename, & surname. This way, each row will be updated individually with a random team from the teams list.
for player in players:
team = random.choice(teams)
query = f"UPDATE trades SET team = '{team}' WHERE date = '{player[0]}' AND forename = '{player[1]}' AND surname = '{player[2]}'"
cursor.execute(query)