Следите за новинками
в нашем Telegram канале. Жми, чтобы подписаться:)
⊗pyPmDBNU 109 of 128 menu
◀ ▶

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:

query = "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:

with 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:

query = "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:

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

Practical tasks

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

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

For everyone whose salary is 500, make it 700.

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

← →
↑
English▼
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline