[英]How to update column value in Postgres table from Python based on condition
我有具有以下值的 postgres 表(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
我的連接字符串
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()
我想根據兩個條件將Active_Status
更新為已過期
Exp_date
小於system date ( todays date)
Active_Status ='active'
預計 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
從 python 為 postgres 編寫的更新查詢如何
在使用數據庫時,我會學會遠離 f 字符串。 我會建議make_dsn
它只是一個 SQL 查詢,Python 並沒有真正進入它。 在 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.
然后您可以將查詢轉移到您的 psycopg2 代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.