Updating Records via SQL Query in Python

Now let's learn how to change records. This is done using the UPDATE command. It has the following syntax:

pythonquery = "UPDATE table SET field = value WHERE condition"

with connection.cursor(dictionary=True) as cursor:
  cursor.execute(query)
  connection.commit()

With the UPDATE command, you must use the commit method:

pythonwith connection.cursor(dictionary=True) as cursor:
  cursor.execute(query)
  connection.commit()

Be careful, if you do not specify a block with WHERE in the query, then during the update all the original records will be replaced by new ones.

Example

Let's change the user's age and salary:

pythonquery = "UPDATE users SET age=20, salary=800 WHERE id=1"

Example

Let's set the salary to 400 and the age to 24 for all users aged 23:

pythonquery = "UPDATE users SET age=24, salary=300 WHERE age=23"

Practical tasks

Задание 1

Using the dump of the users table you created earlier, restore it to its original state.

Задание 2

For a user with id 4, set the age to 35 years.

Задание 3

For everyone whose salary is 500, make it 700.

Задание 4

For workers with id greater than 2 and less than 5 inclusive, set the age to 23.