[英]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.