PostgreSQL Python: Update Data in a Table
Summary : in this tutorial, you will learn how to update data in a PostgreSQL table from a Python program.
This tutorial picks up from where the Inserting Data Into Table Tutorial left off.
Steps for updating data in a PostgreSQL table from Python
To update data from a table in Python, you follow these steps:
cursor
object from the
connection
object.
execute()
method of the
cursor
object.
commit()
method of the
connection
object.
rowcount
property of the
cursor
object.
Updating data in a table example
We will use the
vendors
table in the
suppliers
database for the demonstration:
1) Creating update.py module
Suppose a vendor changed its name, you need to reflect these changes in the
vendors
table.
To achieve this, you can define a function
update_vendor()
, which updates the vendor name based on the vendor id.
First, create a new module called
update.py
in the project directory.
Second, define
update_vendor()
function in the
update.py
module:
2) Execute the update.py module
First, open the Command Prompt on Windows or Terminal on Unix-like systems.
Second, execute the
update.py
module:
3) Verify the update
First, connect to the PostgreSQL server using the
psql
client tool:
Second, change the current database to
suppliers
:
Third, retrieve data from the
vendors
table with the vendor id 1:
Output: