Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update column in rows with variable for each row

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading