简体   繁体   中英

How to update column value in Postgres table from Python based on condition

I have postgres table (Alpha) with following values

Alpha

ID  Exp_Date     Active_Status
1   7-12-2021    active
2   8-12-2021    active
3   15-12-2021   active
4   15-12-2021   active
5   11-12-2021   expired
6   1-12-2021    expired
7   6-12-2021    expired

My Connection String

postgres_str = f'postgresql://{username}:{password}@{host}:{port}/{dbname}'
# Create the connection and cursor
rds_conn = psycopg2.connect(postgres_str)
rds_cur = rds_conn.cursor()

I want to update the Active_Status to expired based on two conditions

  1. if Exp_date is less than system date ( todays date)
  2. if Active_Status ='active'

Expected Output

ID  Exp_Date     Active_Status
1   7-12-2021    expired
2   8-12-2021    expired
3   15-12-2021   active
4   15-12-2021   active
5   11-12-2021   expired
6   1-12-2021    expired
7   6-12-2021    expired

How could the update query written from python for postgres

  1. I would learn to stay away from f strings when working with databases. I would suggest make_dsn

  2. It is just a SQL query, Python does not really enter in to it. Test in psql:

BEGIN;  
update 
   "Alpha" 
set 
   "Active_Status" = 'expired' 
where 
   "Exp_date" < current_date 
and 
   "Active_Status" = 'active';
--Then either COMMIT; or ROLLBACK; depending on whether it worked or not.

Then you can transfer the query to your psycopg2 code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM